在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
#### Go 结构体方法 package main import "fmt" type Person struct { Name string Age int } func (p Person) say(){ fmt.Printf("I am %s and %d years old\n",p.Name,p.Age) } func main(){ var p Person p.Name = "aaa" p.Age = 11 var p2 Person p2.Name = "bbb" p2.Age = 22 // 调用实例方法 p.say() // I am aaa and 11 years old p2.say() //I am bbb and 22 years old }
package main import ( "fmt" ) type Student struct { Name string Age int Skills []string } // 这里类似引用 func (s *Student)Learn(skill string) { // 通过学习,会一个技能 // append 底层会自动make s.Skills = append(s.Skills,skill) } func (s Student) Show(){ for _,skill := range s.Skills { fmt.Printf("I am %s,I am %d years old,and %sing is my skill\n",s.Name,s.Age,skill) } } func main(){ var s1 Student s1.Name = "小明" s1.Age = 20 s1.Learn("fish") s1.Learn("learn") var s2 Student s2.Name = "小红" s2.Age = 18 s2.Learn("Sing") s2.Learn("paint") // 调用方法 s1.Show() s2.Show() //I am 小明,I am 20 years old,and fishing is my skill //I am 小明,I am 20 years old,and learning is my skill //I am 小红,I am 18 years old,and Singing is my skill //I am 小红,I am 18 years old,and painting is my skill }
package main import "fmt" type Student struct { Name string Age int } func (s Student) setName(){ // 接收者为实例变量的副本,在方法内更改值不会影响原来的值 s.Name = "aaaaaa" } func (s *Student) setAge(){ // 接收者为实例变量地址的副本,在方法内更改值会改变原来的值 s.Age = 21 } func main(){ var s1 Student var s2 Student s1.Name = "a" s1.Age = 10 s2.Name = "b" s2.Age = 10 s1.setName() fmt.Println(s1)// {a 10} s2.setAge() fmt.Println(s2) //{b 21} }
package main import "fmt" type Student struct { Name string Age int } //也可以使用值类型调用此方法 func (s *Student) setName(){ s.Name = "bbbb" } //也可以使用指针类型调用此方法 func (s Student) showName(){ fmt.Println(s.Name) } // 默认fmt.Println 会调用此方法 func (s Student) String() string{ return fmt.Sprintf("I am %s,i am %d years old",s.Name,s.Age) } func main(){ var s Student s.Name = "a" s.Age = 20 fmt.Println(s) // I am a,i am 20 years old s.setName() // 值类型的调用接收者为指针类型的方法 s.showName() // bbbb fmt.Println(s) // I am bbbb,i am 20 years old var s1 *Student = new(Student) s1.Name = "b" s1.Age = 10 fmt.Println(s1) // I am b,i am 10 years old s1.setName() // s1.showName() // bbbb 指针类型的调用接收者为值类型的方法 // 在这里需要说一下 // 标准的调用 方式应该是 (*s1).showName() // Go 编译器在底层自动做了解引用,所以可以简化成s1.showName // 总之,不管是指针接收者还是值接收者,统一使用实例.方法名就可以; fmt.Println(s1) //I am bbbb,i am 10 years old }
|
请发表评论