如何在golang中使用相同的接口实现不同的函数?

huangapple go评论89阅读模式
英文:

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

问题

我已经定义了一个名为session的接口,并且我有SessionASessionB,代码如下:

type Session interface {
    StartSession()
}

type SessionA struct {
    jobs string
}

type SessionB struct {
    foods string
}

func (sessionA *SessionA) StartSession() {
    fmt.Printf("开始做%s\n", sessionA.jobs)
}

func (sessionB *SessionB) StartSession() {
    fmt.Printf("开始吃%s\n", sessionB.foods)
}

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

func main() {
    sessionType := 1 // 可能是2,这只是一个例子
    var s Session
    if sessionType == 1 {
        s = &SessionA{jobs: "工作任务"}
    } else {
        s = &SessionB{foods: "食物"}
    }
    
    s.StartSession()
}

但是我得到了这个错误信息:s.StartSession() type interface {} is interface with no methods,我的问题是如何使用同一个变量来调用不同的StartSession方法。

英文:

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

答案1

得分: 2

需要进行两个修复:

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

以下是代码:

var s Session        // 将变量声明为 Session 类型,以便我们可以调用 StarSession 方法
if sessionType == 1 {
	s = &SessionA{}  // 注意此行上的 & 符号
} else {
	s = &SessionB{}  // 注意此行上的 & 符号
}
英文:

Two fixes are needed:

  • To call an interface method on some variable, declare the variable as the interface type.
  • The pointer receiver implements the method. Assign pointers to the interface variable.

Here's the code:

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
}

答案2

得分: 1

你可以编写一个接受接口的函数。

package main

import "fmt"

type Session interface {
    StartSession()
}

type SessionA struct {
    jobs string
}

type SessionB struct {
    foods string
}

func (sessionA *SessionA) StartSession() {
    fmt.Printf("开始做%s\n", sessionA.jobs)
}

func (sessionB *SessionB) StartSession() {
    fmt.Printf("开始吃%s\n", sessionB.foods)
}

func main() {
    sessionType := 1 // 可能是2,这里只是示例
    sessionA := &SessionA{
        jobs: "工作1",
    }
    sessionB := &SessionB{
        foods: "食物1",
    }

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

func runSession(s Session) {
    s.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()
}

答案3

得分: 0

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

type Session interface { //共同的行为
    StartSession()
}

type SessionA struct {
    jobs string
}

type SessionB struct {
    foods string
}

func (sessionA *SessionA) StartSession() {
    fmt.Printf("开始做%s\n", sessionA.jobs)
}

func (sessionB *SessionB) StartSession() {
    fmt.Printf("开始吃%s\n", sessionB.foods)
}

你的主函数可以是这样的:

func main() {
	sessionToExcecute := 1
	sessions := map[int]Session{
		1: &SessionA{jobs: "一些工作"},
		2: &SessionB{foods: "一种食物"},
	}
	sessions[sessionToExcecute].StartSession()
}
英文:

you can use an strategy pattern, with that appproach you are able to extend your code in case you need it. The object that is intanced on runtime depends on some context.

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

your main could be:

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

huangapple
  • 本文由 发表于 2022年5月16日 23:57:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/72262118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定