为什么go编译器将我的变量标记为未使用?
我关于 StackOverflow 的第一个问题:D
我正在运行 1.16。我创建了这个函数:
func (_m *MyPool) InChannel(outs ...chan interface{}) error {
for _, out := range outs {
out = _m.inChan
}
return nil
}
MyPool 是一种工作池类型,其中包含以下成员:
type MyPool struct {
inChan chan interface{}
}
我的主要问题是 Go 正在标记out循环变量在InChannel. 这是为什么?我确实在用...
抱歉,我是 StackOverflow 的菜鸟,所以我正在编辑以澄清一点。我确实想分配,而不是发送。这是因为发送方将有一个outChan chan interface{}作为成员变量,并将通过以下方式发送值:
func (s *Sender) Out(out interface{}) {
select {
case <-s.Ctx.Done():
return
case s.outChan <- out:
return
}
}
编辑:所以我最终通过执行以下操作来解决它:
func (m *MyPool) InChannel(outs ...*chan interface{}) error {
for _, out := range outs {
*out = m.inChan
}
return nil
}
回答
你并没有“真正”使用它。您将某些内容分配给您未读取的变量,因此分配无效,因此基本上您没有使用该变量。
注意=是赋值。如果要在频道上发送某些内容,请使用send语句:
out <- _m.inChan
或者,也许您想更改out代表的值?out是一个循环变量,它是您范围内的切片元素的副本。赋值给out只给循环变量赋值,而不是给切片元素赋值。
通常,您可以通过使用如下索引表达式分配值来更改切片元素:
s := []int{1, 2, 3}
for i := range s {
s[i] = 10 // Assign a value to the slice elements
}
但是,在您的情况下,这没有好处,因为您正在遍历可变参数的切片。
- This has nothing to do with the variadic parameter. You have a loop variable `out` to which you assign a value, yet you never read that variable. So it has no use, it's classified as "unused". Go does not allow unused variables.
- *"the assignment does take effect"* -- @eloib not it doesn't, `out` in `InChannel` is a copy of the caller's value, all you're doing is assigning to the copy, the caller's value won't change. Use pointer indirection if you have to do something like that.