继承 封装 多态
定义结构体
//定义老师的结构体
type Teacher struct {Name stringAge intSchool string
}func main() {var t1 Teacherfmt.Println(t1)t1.Name = "tom"t1.Age = 20t1.School = "school"fmt.Println(t1)
}
结构体实例的创建
package mainimport "fmt"//定义老师的结构体
type Teacher struct {Name stringAge intSchool string
}func main() {var t1 Teacherfmt.Println(t1)t1.Name = "tom"t1.Age = 20t1.School = "school"fmt.Println(t1)var t2 Teacher = Teacher{"liu", 32, "rrr"}fmt.Println(t2)//指针*var t *Teacher = new(Teacher)//t是指针 t其实指向的就是地址 应该给这个地址的执行的对象的字段赋值(*t).Name = "ma"(*t).Age = 23t.School = "daxue"fmt.Println(t)var t6 *Teacher = &Teacher{"sa", 46, "eda"}fmt.Println(t6)
}
//指针*
结构值之间的转换
方法 行为
package mainimport "fmt"//定义Person结构体
type Person struct {Name string
}func (p Person) test() {fmt.Println(p.Name)
}
func main() {//创建结构体对象var p Personp.Name = "tom"p.test()
}
改变值
package mainimport "fmt"//定义Person结构体
type Person struct {Name string
}func (p Person) test() {fmt.Println(p.Name)
}//*是指针
func (p *Person) test01() {fmt.Println()fmt.Println((*p).Name)
}
func main() {//创建结构体对象var p Personp.Name = "tom"p.test()p.Name = "sasa"fmt.Printf("p的地址为:%p \n", &p)(&p).test()fmt.Println(p)
}
改变值用指针
package mainimport "fmt"type interger intfunc (i interger) print() {fmt.Println("i= ", i)
}func (i *interger) print01() {(*i) = 30fmt.Println("i=", *i)
}
func main() {var i interger = 20i.print()fmt.Println(i)var i01 interger = 5i01.print01()fmt.Println("i01=", i01)
}
其他包被访问用大写
toString
package mainimport "fmt"type Student struct {Name stringAge int
}func (s Student) toString() string {str := fmt.Sprintf("Name = %v, Age = %v", s.Name, s.Age)return str
}
func (s *Student) toString2() string {str := fmt.Sprintf("Name = %v, Age = %v", s.Name, s.Age)return str
}func main() {stu := Student{Name: "tom",Age: 20,}fmt.Println(stu)fmt.Println(&stu)
}
方法和函数的区别
import "fmt"type Student struct {Name string
}//定义方法必须定义指定的类型
func (s Student) test01() {fmt.Println(s.Name)
}//定义函数
func method01(s Student) {fmt.Println(s.Name)
}
func main() {//调用函数var s Student = Student{"tom"}method01(s)//方法调用s.test01()
}
函数定义的是指针必须传递的是指针,函数定义的是值传递 必须是值类型
package mainimport "fmt"type Student struct {Name string
}//定义函数
func method01(s Student) {fmt.Println(s.Name)
}func method02(s *Student) {fmt.Println((*s).Name)
}
func main() {//函数定义的是指针必须传递的是指针//函数定义的是值传递 必须是值类型var s Student = Student{"tom"}method01(s)method02(&s)
}
对于方法来说,接收者为值类型,可以传入指针类型,接受者为指针类型,可以传入值类型
package mainimport "fmt"type Student struct {Name string
}//定义方法
func (s Student) test01() {fmt.Println(s.Name)
}
func (s *Student) test02() {fmt.Println((*s).Name)
}func main() {var s Student = Student{"yy"}s.test01()//虽然用指针类型调用,但是传递还是安装值传递的形式(&s).test01()(&s).test02()s.test02()
}