Go语言结构体之属性及函数
- 属性和函数定义
两种作用域
目录结构
├── demo │ └── demo.go ├── go.mod └── main.go
demo.go文件
package demo import "fmt" type Dog struct { ID int //属性 Name string Age int } func (d *Dog)Run() { //Run 大写字母开头的方法为共有方法 fmt.Println("ID:",d.ID,"DOG is running") } func (d *Dog)run1() { //run1 小写字母开头的方法为私有方法 fmt.Println("ID:",d.ID,"DOG is running") }
main.go文件
package main import "./demo" func main() { dog := new(demo.Dog) dog.ID = 1 //属性赋值 dog.Name = "GG" dog.Age = 5 dog.Run() //ID: 1 DOG is running //dog.run1() // 不能调用私有方法 }
Comment here is closed