dongmo3413 2017-04-01 05:21
浏览 44
已采纳

如何在Go中将包分配给变量?

First of all, the word "variable" might be wrong in the question but I assume the detailed question explains why I'm using the word "variable".

I have two packages with different names but the exact same function(s).

Depending on the input of the user I want to use the function of a package. But instead of switching over the packages I would like to assign the package to a new function with a generic name, how to do this? And if it's not possible, why?

// foo/bar.go

package foo

func Test() {
    fmt.Println("hola from bar")
}

// baz/bar.go

package baz

func Test() {
    fmt.Println("hola from baz")
}

// main.go

package main

import (
    "foo"
    "baz"
)

func main() {

    thePackage := flag.String("package", "foo", "a package")

    if thePackage == "foo" {
        howToSetThis := foo // How to do this?
    } else {
        howToSetThis := baz // How to do this?
    }

    howToSetThis.Test() // execs Println from one of the two bar.go files

}

In JavaScript I would do something like (simplified):

function foo(){
  console.log("hola from foo")
}

function baz(){
  console.log("hola from baz")
}

if(somethingInput == "foo"){
  var howToSetThis = foo;
} else {
  var howToSetThis = baz;
}

howToSetThis();
  • 写回答

2条回答 默认 最新

  • dongtu1789 2017-04-01 05:34
    关注

    You could define a interface in a package that requires the functions you want to have in those two packages .

    package intfc
    
    type Intfc interface {
        Test()
    }
    

    And then two structs in different packages which implements that interface

    package foo
    
    import "fmt"
    
    type Foo struct {
    
    }
    
    func (f Foo) Test() {
        fmt.Println("hola from foo")
    }
    

    and

    package baz
    
    import "fmt"
    
    type Baz struct {
    
    }
    
    func (f Baz) Test() {
        fmt.Println("hola from baz")
    }
    

    And then in main do something like this:

    package main
    
    import (
        "foo"
        "baz"
        "intfc"
        "flag"
    )
    
    func main() {
    
        var howToSetThis intfc.Intfc
    
        thePackage := flag.String("package", "foo", "a package")
    
        if *thePackage == "foo" {
            howToSetThis = foo.Foo{}
        } else {
            howToSetThis = baz.Baz{}
        }
    
        howToSetThis.Test() // execs Println from one of the two bar.go files
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来