



Declaring Structs
package main
import "fmt"
type person struct {
firstName string
lastName string
}
func main() {
alex := person{firstName: "Alex", lastName: "Anderson"}
fmt.Println(alex)
}

Updating Structs Values
package main
import "fmt"
type person struct {
firstName string
lastName string
}
func main() {
var alex person
alex.firstName = "Alex"
alex.lastName = "Anderson"
fmt.Println(alex)
fmt.Printf("%+v", alex)
}

Embedding Structs
package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contact contactInfo
}
func main() {
maxwell := person{
firstName: "Maxwell",
lastName: "Pan",
contact: contactInfo{
email: "maxwell@gmail.com",
zipCode: 96500,
},
}
fmt.Printf("%+v", maxwell)
}

Structs with Receiver Functions
package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contactInfo
}
func main() {
maxwell := person{
firstName: "Maxwell",
lastName: "Pan",
contactInfo: contactInfo{
email: "maxwell@gmail.com",
zipCode: 96500,
},
}
maxwell.updateName("Max")
maxwell.print()
}
func (p person) updateName(newFirstName string) {
p.firstName = newFirstName
}
func (p person) print() {
fmt.Printf("%+v", p)
}

Pass By Value


Structs with Pointers
package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contactInfo
}
func main() {
maxwell := person{
firstName: "Maxwell",
lastName: "Pan",
contactInfo: contactInfo{
email: "maxwell@gmail.com",
zipCode: 96500,
},
}
maxwellPointer := &maxwell
maxwellPointer.updateName("Max")
maxwell.print()
}
func (pointerToPerson *person) updateName(newFirstName string) {
(*pointerToPerson).firstName = newFirstName
}
func (p person) print() {
fmt.Printf("%+v", p)
}

Pointer Operations


Pointer Shortcut

package main
import "fmt"
type contactInfo struct {
email string
zipCode int
}
type person struct {
firstName string
lastName string
contactInfo
}
func main() {
maxwell := person{
firstName: "Maxwell",
lastName: "Pan",
contactInfo: contactInfo{
email: "maxwell@gmail.com",
zipCode: 96500,
},
}
maxwell.updateName("Max")
maxwell.print()
}
func (pointerToPerson *person) updateName(newFirstName string) {
(*pointerToPerson).firstName = newFirstName
}
func (p person) print() {
fmt.Printf("%+v", p)
}

Gotchas With Pointers
package main
import "fmt"
func main() {
mySlice := []string{"Hi", "There", "How", "Are", "You"}
updateSlice(mySlice)
fmt.Println(mySlice)
}
func updateSlice(s []string) {
s[0] = "Bye"
}
Test Your Knowledges: Pointers











Reference vs Value Type















33万+

被折叠的 条评论
为什么被折叠?



