继承 封装 多态
定义结构体
//定义老师的结构体
type Teacher struct {
Name string
Age int
School string
}
func main() {
var t1 Teacher
fmt.Println(t1)
t1.Name = "tom"
t1.Age = 20
t1.School = "school"
fmt.Println(t1)
}
结构体实例的创建
package main
import "fmt"
//定义老师的结构体
type Teacher struct {
Name string
Age int
School string
}
func main() {
var t1 Teacher
fmt.Println(t1)
t1.Name = "tom"
t1.Age = 20
t1.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 = 23
t.School = "daxue"
fmt.Println(t)
var t6 *Teacher = &Teacher{"sa", 46, "eda"}
fmt.Println(t6)
}
//指针*
结构值之间的转换
方法 行为
package main
import "fmt"
//定义Person结构体
type Person struct {
Name string
}
func (p Person) test() {
fmt.Println(p.Name)
}
func main() {
//创建结构体对象
var p Person
p.Name = "tom"
p.test()
}
改变值
package main
import "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 Person
p.Name = "tom"
p.test()
p.Name = "sasa"
fmt.Printf("p的地址为:%p \n", &p)
(&p).test()
fmt.Println(p)
}
改变值用指针
package main
import "fmt"
type interger int
func (i interger) print() {
fmt.Println("i= ", i)
}
func (i *interger) print01() {
(*i) = 30
fmt.Println("i=", *i)
}
func main() {
var i interger = 20
i.print()
fmt.Println(i)
var i01 interger = 5
i01.print01()
fmt.Println("i01=", i01)
}
其他包被访问用大写
toString
package main
import "fmt"
type Student struct {
Name string
Age 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 main
import "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 main
import "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()
}