go语言的结构体(struct)

简单介绍下结构体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", "[email protected]", 21, true}
        lisa.notify()
      
      // 使用user的指针赋值
        bill := &user{"lisa", "[email protected]", 43, false}
        bill.notify()

        lisa.changeEmail("[email protected]")
        lisa.notify()
}

结果:

go build struct.go

go run struct.go

运行结果:

Send email to tom 
Send email to lisa 
Send email to tom <[email protected]>

你可能感兴趣的:(go语言的结构体(struct))