I have defined an interface named session, and I have SessionA and SessionB like this
type Session interface {
StartSession()
}
type SessionA struct {
jobs string
}
type SessionB struct {
foods string
}
func (sessionA *SessionA) StartSession() {
fmt.Printf("begin to do %s\n", sessionA.jobs)
}
func (sessionB *SessionB) StartSession() {
fmt.Printf("begin to eat %s\n", sessionB.foods)
}
In my main function I want to define a parameter which can call StartSession automatically
func main() {
sessionType := 1 // maybe 2, just example
var s interface{}
if sessionType == 1 {
s = SessionA{}
} else {
s = SessionB{}
}
s.StartSession()
}
but I get this s.StartSession() type interface {} is interface with no methods, my question is how can I use same variable to call different StartSession()
var s Session. Define the variable using the correct type.var s Session2) you need to assign pointers of SessionA and SessionB to s. ies = &SessionA{}. The reason being pointer receiver methods won't be in the method set of your normal variable.