简单介绍下结构体struct:
type name struct {
xx1 类型
xx2 类型
...
}
package main
import "fmt"
type user struct {
name string
email string
age int
privileged bool
}
func (u user) notify () {
fmt.Printf("Send email to %s <%s>\n", u.name, u.email)
}
func (u *user)changeEmail(email string) {
u.email = email
}
func main () {
// struct 定义变量时,不能少字段
lisa := user{"tom", "xx@gmail.com", 21, true}
lisa.notify()
// 使用user的指针赋值
bill := &user{"lisa", "sss@gmail.com", 43, false}
bill.notify()
lisa.changeEmail("5423131@gmail.com")
lisa.notify()
}
结果:
go build struct.go
go run struct.go
运行结果:
Send email to tom <xx@gmail.com>
Send email to lisa <sss@gmail.com>
Send email to tom <5423131@gmail.com>
网友评论