GO语言method
来源:互联网 发布:淘宝卖家需要的软件 编辑:程序博客网 时间:2024/06/13 23:58
方法就相当于类的行为,对应于固定的结构体
package mainimport "fmt"type A struct{ Name string } type B struct{ Name string } func (a A)Print(){ fmt.Println("A")}func (b B)Print(){ fmt.Println("B")}func main(){ a:=A{} a.Print()//achieve the method of struct A b:=B{} b.Print()//thougth the name is same it will not make trouble}
通过a.Print和b.Print那么就是针对不同类型的所以可以分辨
但是如果加一个
func (b B)Print(int){ fmt.Println("B")}
因为没有重载功能它并不能够区分应该使用那么一个函数
要在receiver中改变值也应该使用指针
试试看类型别名能否添加method
package mainimport "fmt"type TZ intfunc (a *TZ)Print(){ fmt.Println("A")}func main(){ var a TZ//though the bottom of the TZ is int we still can append method a.Print()}
这更加证明了虽然是别名但是到底还是不同,因为内置类型如int等就无法添加方法
方法只能对当前包的类型进行绑定
method-value和method-expression
package mainimport "fmt"type TZ intfunc (a *TZ)Print(){ fmt.Println("A")}func main(){ var a TZ a.Print()//method value (*TZ).Print(&a)//method expression}
方法的权限问题
package mainimport "fmt"type A struct{ name string//private if 'n' public if 'N'} //private and public is for package only the Name can be used in other package func (a *A)Print(){ a.name="123" fmt.Println(a.name)}func main(){ a:=A{} a.Print() fmt.Println(a.name)}
声明:
m map[interface{}]bool
选择类型为interface{}是有原因的,因为这样可以保证元素可以是任何类型的
阅读全文
0 0
- Go语言基础:method
- GO语言method
- Go语言学习笔记 --- method
- go语言学习-method和function
- go 语言type Method Values vs. Method Expressions
- Go语言学习之method(The way to go)
- go - method方法
- go method使用
- GO面向对象:method
- Go方法method
- 【Go】Go语言初学
- Go语言
- Go语言
- Go语言
- go语言
- go语言
- Go语言
- Go语言
- rhel7中,targetcli使用两位数的分区后缀名字(比如sda10)而导致的问题
- java单链表的翻转
- 解决mybatis generator生成实体类和数据库字段名不一致
- [UIViewController _loadViewFromNibNamed:bundle:] loaded the nib but the view outlet was not set
- android studio 中 Error:(12, 23) 错误: 程序包org.apache.http不存在
- GO语言method
- solr学习笔记 -- day05 solrJ的使用
- 从内核文件系统看文件读写过程
- USCAO-Section 1.3 Combination Lock
- 慕课网Python3.x开发简单爬虫及完整源码
- leapmotion simple control 插件的使用
- Codeforces 750 D New Year and Fireworks
- 将数据的初始化放到docker中的整个工作过程(问题记录)
- java设计模式之单例模式5种方法及优缺点小结