i具有setter函数的结构
package main
type Person struct {
Name string
Age int
}
func (p *Person) SetName(name string) {
p.Name = name
}
func SomeMethod(human interface{}){
// I call the setter function here, but doesn't seems exist
human.SetName("Johnson")
}
func main(){
p := Person{Name : "Musk"}
SomeMethod(&p)
}
有以下错误的错误:
human.setname undefined(键入接口{}是与no的接口 方法(
似乎func SetName
不包括在 SomeMethod
为什么这样?任何答案都将不胜感激!
创建与setName
的接口并在Person
结构上实现它,然后调用SomeMethod
以设置Person
package main
import "fmt"
type Person struct {
Name string
Age int
}
type Human interface{
SetName(name string)
}
func (p *Person) SetName(name string) {
p.Name = name
}
func SomeMethod(human Human){
human.SetName("Johnson")
}
func main(){
p := &Person{Name : "Musk"}
SomeMethod(p)
fmt.Println(p)
}
去操场
使用getter方法来获取任何struct通过人类接口实现 Human
接口上的getter属性
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
type Person2 struct{
Name string
Age int
}
type Human interface{
getName() string
}
func (p *Person2) getName() string{
return p.Name
}
func (p *Person) getName() string{
return p.Name
}
func SomeMethod(human Human){
fmt.Println(human.getName())
}
func main(){
p := &Person{Name : "Musk"}
SomeMethod(p)
p2 := &Person2{Name: "Joe"}
SomeMethod(p2)
}
去操场