如何在golang中使用相同的接口实现不同的功能

How can I implement different functions using the same interface in golang

我已经定义了一个名为 sessioninterface,并且我有 SessionASessionB 这样的

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)
}

在我的 main 函数中,我想定义一个可以自动调用 StartSession 的参数

func main() {
    sessionType := 1 // maybe 2, just example
    var s interface{}
    if sessionType == 1 {
        s = SessionA{}
    } else {
        s = SessionB{}
    }
    
    s.StartSession() 
}

但我明白了 s.StartSession() type interface {} is interface with no methods,我的问题是如何使用相同的变量调用不同的 StartSession()

You can write a function that accept interface

package main

import "fmt"

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)
}

func main() {
    sessionType := 1 // maybe 2, just example
    sessionA:= &SessionA{
        jobs: "job1",
    }
    sessionB := &SessionB{
        foods: "food1",
    }


    if sessionType == 1 {
        runSession(sessionA)
    } else {
        runSession(sessionB)
    }
    
    
}

func runSession(s Session) {
    s.StartSession()
}

需要两个修复:

  • 要在某个变量上调用接口方法,请将变量声明为接口类型。
  • 指针接收器实现了方法。将指针分配给接口变量。

代码如下:

var s Session        // Declare variable as Session so we can call StarSession
if sessionType == 1 {
    s = &SessionA{}  // note & on this line
} else {
    s = &SessionB{}  // note & on this line
}

您可以使用策略模式,通过这种方法您可以在需要时扩展您的代码。在运行时实例化的对象取决于某些上下文。

type Session interface { //the common behaviour
    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)
}

你的主要可能是:

func main() {
    sessionToExcecute := 1
    sessions := map[int]Session{
        1: &SessionA{jobs: "some job"},
        2: &SessionB{foods: "a food"},
    }
    sessions[sessionToExcecute].StartSession()
}