为什么我的for循环会抛出“意外的分号或换行符”错误?

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

Go- Why Does My For Loop Throw "Unexpected Semi-colon or New-line"?

问题

我正在编写一个掷骰子的函数。为了将每个骰子的结果相加,我使用了一个for循环将结果添加到一个输出变量中。然而,在我尝试构建代码时,出现了一个错误:

语法错误:意外的分号或换行符,期望 {

这个错误出现在初始化for循环的那一行。以下是我的代码:

	for i := 0; i < [0]si; i++ {
		output := output + mt.Intn([1]si)
	}

si只是一个包含两个值的int数组,mt是我在导入math/rand时给它起的名字。

英文:

I'm writing a dice rolling function. In order to add the result of each die, I added to an output variable using a for loop. However, I'm getting an error thrown when I attempt to build;

>syntax error: unexpected semicolon or newline, expecting {

This was thrown on the line initializing the for loop.
Here is my code:

	for i := 0; i &lt; [0]si; i++ {
		output := output + mt.Intn([1]si)
	}

si is simply an int array holding 2 values, and mt is the name I gave to math/rand when I imported it.

答案1

得分: 2

你的循环有几个问题:

  1. 使用方括号的方式有些奇怪。在类型定义之外,方括号应该放在切片/数组名称之后,例如x[i]将给出切片x的第i个元素。
  2. 循环体内没有引用i,因此每次循环迭代都会执行相同的操作。
  3. 你可能应该写成output = output + ...,而不需要冒号。否则,每次循环迭代都会声明一个新的变量output,并且在循环之后立即被忘记,使得循环没有任何效果。

编译器错误可能是由这些问题中的第一个引起的。

英文:

Your loop has several problems:

  1. The use of square brackets is odd. Outside of type definitions, these go after slice/array names, e.g. x[i] would give you the ith element of the slice x.
  2. There is no reference to i inside the loop body, and thus each iteration of the loop will do the same thing.
  3. You should probably write output = output + ... without the colon. Otherwise, a new variable output is declared during each iteration of the loop, and forgotten immediately after so that the loop has no effect.

The compiler error is probably caused by the first of these problems.

答案2

得分: 0

在Go语言中,你可以使用varname[idx]的方式访问数组,就像大多数其他语言一样。只有在声明一个新的类型为si的数组时,你才会使用[size]si的前缀语法。你之所以得到这个错误是因为你的代码在语法上是无效的。你试图将i与一个大小为0的si数组进行比较。

英文:

You access an array with varname[idx] in Go, just like in most other languages. It's only when declaring a new array of type si that you use the [size]si prefix syntax. You're getting the error because your code is syntactically invalid. You're trying to compare i to an array of 0 si s.

huangapple
  • 本文由 发表于 2016年2月14日 06:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/35385880.html
匿名

发表评论

匿名网友

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

确定