方法的使用,請看本天師的代碼
//Golang的方法定義 //Golang中的方法是作用在特定類型的變量上,因此自定義類型,都可以有方法,不僅僅是struct //定義:func (recevier type) methodName(參數列表)(返回值列表){} //方法和函數的區別 /* 1,函數調用:function(variable,參數列表) 2, 方法,variable.function(參數列表) 方法的控制,通過大小寫空格控制 */
。。。。
package main //Golang的方法定義 //Golang中的方法是作用在特定類型的變量上,因此自定義類型,都可以有方法,不僅僅是struct //定義:func (recevier type) methodName(參數列表)(返回值列表){} import "fmt" type integer int func (p integer) print() { fmt.Println("p is:", p) } //這里傳遞的是副本,想改變p的值,需要傳遞指針 func (p *integer) set(b integer) { *p = b } type Student struct { Name string Age int Score int sex int } //這里需要接受指針 *Student(接收者),否則修改不了值 func (p *Student) init(name string, age int, score int) { p.Name = name p.Age = age p.Score = score fmt.Println(p) } func (p Student) get() Student { return p } func main() { var stu Student //修改地址的寫法(&stu).init //但是go可以自動知道,接受者是指針,這里stu就傳遞地址 stu.init("stu", 18, 99) stu1 := stu.get() fmt.Println(stu1) //type integer方法 var a integer a = 100 a.print() a.set(1000) a.print() }