I have struct with setter function
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)
}
Got an error as follows :
human.SetName undefined (type interface {} is interface with no methods)
seems like func SetName
doesn't included in SomeMethod
Why is it so? Any answer will be highly appreciated !
Create an interface with setName
and implement it on Person
struct then call SomeMethod
to set the value of 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)
}
To get the name using getter method for any struct pass through Human interface implement getter property on Human
interface
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)
}