在Go语言中没有匿名数组。

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

No anonymous array in go?

问题

代替这样写:

var adapters[]LogicAdapter
adapter1 := &ExampleAdapter{0.9}
adapter2 := &ExampleAdapter{0.8}
adapters = append(adapters, adapter1, adapter2)
bot := ChatterBot{"Charlie", MultiLogicAdapter{adapters}}

我尝试了这样写:

bot := ChatterBot{
    "Charlie", 
    MultiLogicAdapter{
        []LogicAdapter{
            &ExampleAdapter{0.9},
            &ExampleAdapter{0.8}
        }
    }
}

但为什么这样写不起作用呢?我看不出语法上有任何问题,就像我创建了一个新的切片并将其放入其中一样。以下是错误信息:

./main.go:16: 语法错误:意外的分号或换行符,期望逗号或}
./main.go:21: 语法错误:意外的分号或换行符,期望逗号或}
./main.go:22: 语法错误:意外的分号或换行符,期望逗号或}
英文:

Instead of doing:

var adapters[]LogicAdapter
adapter1 := &ExampleAdapter{0.9}
adapter2 := &ExampleAdapter{0.8}
adapters = append(adapters, adapter1, adapter2)
bot := ChatterBot{"Charlie", MultiLogicAdapter{adapters}}

I tried:

bot := ChatterBot{
    "Charlie", 
    MultiLogicAdapter{
        []LogicAdapter{
            &ExampleAdapter{0.9},
            &ExampleAdapter{0.8}
        }
    }
}

But why this won't work? I cannot see any problems with the syntax, it's like I were creating a new slice and putting it into there. Here are the errors:

./main.go:16: syntax error: unexpected semicolon or newline, expecting comma or }
./main.go:21: syntax error: unexpected semicolon or newline, expecting comma or }
./main.go:22: syntax error: unexpected semicolon or newline, expecting comma or }

答案1

得分: 2

你只需要在&ExampleAdapter{0.8}后面和结束其他元素的闭合括号后面加上逗号。Go语法非常严格。即使是最后一个元素,如果闭合括号不在同一行,你也需要在行尾加上逗号。这就是错误信息的意思。你的代码应该像这样:

bot := ChatterBot{
	"Charlie",
	MultiLogicAdapter{
		[]LogicAdapter{
			&ExampleAdapter{0.9},
			&ExampleAdapter{0.8},
		},
	},
}
英文:

You just need a comma at the end of &ExampleAdapter{0.8} and after the closing braces that end the other elements.. Go syntax is pretty strict. If you don't have the closing brace on the same line, you need to end the line with a comma, even if it's the last element. That's what the error message is saying. Your code should look like this:

bot := ChatterBot{
	"Charlie",
	MultiLogicAdapter{
		[]LogicAdapter{
			&ExampleAdapter{0.9},
			&ExampleAdapter{0.8},
		},
	},
}

huangapple
  • 本文由 发表于 2017年2月8日 10:31:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/42103654.html
匿名

发表评论

匿名网友

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

确定