1、方法定义
package main
import "fmt"
type TwoInts struct {
a int
b int
}
func main() {
t1 := new(TwoInts)
t1.a = 1;
t1.b = 2;
fmt.Printf("the sum is %d\n", t1.add())
}
// 这个add函数相当于是绑定到了TwoInts的实例t1上面了
// add方法名前面的是指定receiver
func (this *TwoInts) add() int {
return this.a + this.b;
}
package main;
import "fmt";
type IntVector []int
type str = string
// 切片的例子
func (v IntVector) Sum() int {
s := 0;
for _, x := range v {
s += x
}
return s
}
func main() {
var iv = IntVector {1,2}
fmt.Printf("test:%d\n", iv.Sum())
}
函数和方法的区别
函数将变量作为参数:Function1(recv)
方法在变量上被调用:recv.Method1()
2、方法的值传递 与 引用传递
package main;
import "fmt";
type Point1 struct {x int}
// 值传递, 在方法内改写x的值,rev引用不会被改变
// 如果写成 *Point1 就会同时改变rev的值
func (rev Point1) Sum() (rslt int) {
rev.x = 2
rslt = rev.x
return rslt
}
func main() {
var iv1 = new(Point1);
fmt.Printf("sum:%d\n", iv1.Sum())
fmt.Printf("iv1:%d\n", iv1.x)
}
6、go里面实现getter/setter
package main;
import "fmt";
type Person struct {
fname string
lname string
}
func (this *Person) FName() string {
return this.fname;
}
func (this *Person) SetFName(fname string) {
this.fname = fname
}
func main() {
var p = new(Person);
p.SetFName("jack ma");
fmt.Println(p.FName())
}
3、继承访问父类方法/属性(内嵌)
package main
import "fmt"
import "math"
type Point struct {
x, y float64
}
type NamePoint struct {
Point
name string
}
func (n *NamePoint) Abs() float64 {
return n.Point.Abs()
}
func (this *Point) Abs() float64 {
return math.Sqrt(this.x * this.x + this.y * this.y)
}
func main() {
// 这就相当于NamePoint是子类, Point是父类
var n1 = &NamePoint {Point{2,3}, "pingfang"}
fmt.Printf("NamePoint=%f\n", n1.Abs())
var n2 = &Point {2,3};
fmt.Printf("Point=%f\n", n2.Abs())
}
4、 多重继承
很简单,嵌入2个类型即可
package main
import "fmt"
type Camera struct{}
type Phone struct{}
func (camera *Camera) TakeAPicture() string {
return "没有美颜的相机是没有灵魂的"
}
func (phone *Phone) MakeACall() string {
return "13352011314"
}
type CameraPhpne struct{
Camera
Phone
}
func main() {
cp := new (CameraPhpne)
fmt.Printf("我是一个牛B的手机, 我能照像: %s\n", cp.TakeAPicture())
fmt.Printf("我是一个牛B的手机, 我能打电话给女神: %s\n", cp.MakeACall())
}
5、重写String()方法自定义输出
package main
import "fmt"
import "strconv"
type TwoInts struct {
a int
b int
}
func (this *TwoInts) String() string {
return "(" + strconv.Itoa(this.a) + "/" + strconv.Itoa(this.b) + ")"
}
func main() {
two1 := new(TwoInts)
two1.a = 12
two1.b = 10
// 以下两个是等价的, 它会调用String()自定义输出
fmt.Printf("two1 is: %v\n", two1)
fmt.Println("two1 is:", two1)
// %T输出 类型的定义
fmt.Printf("two1 is: %T\n", two1)
// %#v 我理解是最屌的, 定义、定义字段都会输出
fmt.Printf("two1 is: %#v\n", two1)
}
网友评论