go的结构体与接口
1.当结构体实现了某个接口的所有方法,结构体指针可转换为接口类型
package main
import "fmt"
type service interface {
Get(string) (string, error)
Print()
}
type node struct {
}
func (n *node) Get(in string) (string, error) {
return in, nil
}
func (n *node) Print() {
fmt.Println("aaa")
}
func main() {
var _ service = new(node)
n := &node{}
var s service = n
ret, _ := s.Get("s")
fmt.Println(ret)
s.Print()
}
2.结构体内嵌接口类型
2.1结构体内嵌匿名接口
2.2结构体内嵌接口变量
3.结构体内嵌结构体类型
3.1结构体内嵌结构体指针
3.2结构体内嵌结构体
4.接口内嵌接口
5.接口之间强转
package main
import (
"fmt"
)
type Student struct {
id int
name string
this Inter
}
type Inter interface {
show()
}
func (s *Student) show() {
fmt.Printf("%d %s\n", s.id, s.name)
}
func (s *Student) GetName() string {
return s.name
}
func main() {
s := &Student{
id: 1,
name: "qwe",
}
s.this = s
s.show()
name := s.this.(interface {
GetName() string
}).GetName()
fmt.Println(name)
}
6.结构体方法值类型和指针类型
package main
import "fmt"
type Student struct {
id int
name string
}
func (s *Student) SetName1(str string) {
s.name = str
}
func (s Student) SetName2(str string) {
s.name = str
}
func main() {
s := &Student{}
s.SetName1("11") //指针类型变量调用 指针类型方法,可以修改值
fmt.Printf("%v\n", s)
s.SetName2("22") //指针类型变量调用 值类型方法,不可以修改值
fmt.Printf("%v\n", s)
s2 := Student{}
s2.SetName1("11") //值类型变量调用 指针类型方法,可以修改值
fmt.Printf("%v\n", s2)
s2.SetName1("12") //值类型变量调用 指针类型方法,可以修改值
fmt.Printf("%v\n", s2)
s2.SetName2("22") //值类型变量调用 值类型方法,不可以修改值
fmt.Printf("%v\n", s2)
(&s2).SetName1("33") //指针类型变量调用 指针类型方法,可以修改值
fmt.Printf("%v\n", s2)
}
7.匿名结构体与匿名接口

浙公网安备 33010602011771号