声明一个没有数据类型的变量。

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

Declare a variable without datatype

问题

我有一段代码,需要一个没有类型声明的变量声明。该变量稍后将被赋予一个接口类型的值。伪代码如下所示:

var client
if some_condn {
   client = ssh.Dial(params)
} else {
   client = my_own_ssh_dial(my_params)
}
session,_ := client.NewSession()

问题是,GO语言不允许没有类型声明的变量声明。有没有办法我可以使用类似于Java中的泛型对象来默认初始化client变量?

谢谢。

英文:

I have a piece of code that needs a variable declaration w/o its type. The variable is assigned a value later and that is an interface. pseudo code will look very similar to this:

var client
if some_condn {
   client = ssh.Dial(params)
} else {
   client = my_own_ssh_dial(my_params)
}
session,_ := client.NewSession()

The problem is GO does not allow a variable declaration w/o type. Is there any way I can use something like an generic Object (from Java) to default client to start with?

TIA

答案1

得分: 6

一个变量在使用之前必须具有类型。最接近无类型变量的东西是类型interface{},它是一个接口类型,但没有可调用的方法。

由于这里的目标是调用NewSession方法,所以声明变量时要使用包含该方法的接口。

var client interface {
    NewSession() (*ssh.Session, error)
}
if some_condn {
    client = ssh.Dial(params)
} else {
    client = my_own_ssh_dial(my_params)
}
session, _ := client.NewSession()
英文:

A variable must have a type in order to use it. The closest thing to an untyped variable would be the type interface{}, which is an interface type, but has no methods to call.

Since the goal here is to call the NewSession method, declare the variable with an interface containing that method.

var client interface {
	NewSession() (*ssh.Session, error)
}
if some_condn {
	client = ssh.Dial(params)
} else {
	client = my_own_ssh_dial(my_params)
}
session, _ := client.NewSession()

答案2

得分: -1

我对Go语言还不太熟悉,但我会试着给出一个答案。如果有错误,请指出。不幸的是,你没有给出足够的代码供我尝试,但基本上,你需要创建自己的类型 my_own_ssh,然后添加一个 Dial 函数。接下来,你需要定义一个接口 Client

type Client interface {
    Dial()
}

然后,在条件检查之前,你可以使用 var client Client 来定义你的 client 变量。为了使接口起作用/有意义,你还需要创建一个具有 my_own_ssh 接收器的 Dial 函数。

我非常乐意接收关于这个答案的反馈,因为我之前说过,我对这个还不太熟悉 声明一个没有数据类型的变量。

英文:

I'm pretty new to Go, but I'll take a stab. If it's wrong, cool. Unfortunately, I don't have enough code from you to actually try and do this - but essentially, you'll need to make your own type my_own_ssh, and then add a Dial function to it. Then, you'll define an

interface Client {
    Dial()
}

And then you can define your client variable with var client Client before the conditional check. You'll also need to create a function Dial that has a my_own_ssh receiver in order for the interface to work/make sense.

I'm very happy to receive feedback on this answer, because like I said - I'm pretty new to it 声明一个没有数据类型的变量。

huangapple
  • 本文由 发表于 2021年8月6日 03:43:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68672654.html
匿名

发表评论

匿名网友

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

确定