go语言学习 - 结构体和方法

package main

import "fmt"

func main(){

  //结构体是值类型,用 "结构体名{成员顺序赋值列表}" 的方法构造赋给一个变量得到的是结构体的值
  h := human{"wengmj",true,40} 

  //结构体不支持继承,但是可以用匿名组合的方式实现类似继承的功能,可以组合值也可以组合指针
  s := student{&h,11,99}

  //如果student匿名组合的human定义了say方法,但是student没有定义 say方法 , 
  //仍然可以对 student 调用say ,这时调用的是 human 的方法(继承)
  fmt.Println(h.say())

  //如果同时student也定义了say 方法,这时就自动调用 studeng 的 say 方法。(方法重写) 
  //这就实现了类似面向对象的继承和覆盖
  fmt.Println(s.say())   
}


type human struct {
	name string
	sex bool
	age int
}

type student struct {
	*human //指针匿名组合
	id int
	score int
}

//方法接受者可以是值也可以是指针,
//调用复合结构的成员变量或成员函数时用值还是指针在go中不在区分 都使用 "." 操作符而不再使用c中的 "->" 操作符 
func (h human) say() string {
	// 这里的方法如果定义为 *human 则方法执行后 h 的变量本身的值会被改掉  
    h.name = "chang only here" 
	return fmt.Sprintf("I am a human my name is %s.",h.name)
}

//函数不管是定义为值接受者还是指针接受者,用指针和值都可以调用 如 h.say() 或 (&h).say() 区别是指针接受者就可以修改原变量的值
func (s *student) say() string {
	return fmt.Sprintf("I am a student my name is %s. my score is %d",s.name,s.score)
}

猜你喜欢

转载自www.cnblogs.com/scala/p/9542175.html