2 回答

TA贡献1844条经验 获得超8个赞
在循环内部,您通过 usingfor重新声明s为新的循环范围变量s :=,如下面的代码所示。您永远不会在其范围内使用该特定变量,因此会出现错误:s declared and not used.
// this instance of s is scoped to the function
var s string
for _, quote := range quotes {
// *** this instance of s is only scoped to loop and it's not actually used within loop ***//
s := fmt.Sprintf("%v: bid $%.02f (%v shares), ask $%.02f (%v shares) [as of %v]\n",
quote.Symbol, quote.BidPrice, quote.BidSize,
quote.AskPrice, quote.AskSize, quote.LastUpdated)
}
相反,s :=改为 this s =,如下所示。但是,您还没有完成,请在下面进一步阅读。
var s string
for _, quote := range quotes {
s = fmt.Sprintf("%v: bid $%.02f (%v shares), ask $%.02f (%v shares) [as of %v]\n",
quote.Symbol, quote.BidPrice, quote.BidSize,
quote.AskPrice, quote.AskSize, quote.LastUpdated)
}
使用上面的代码将覆盖s循环的每次迭代的值。如果您想保留循环中生成的每个字符串并将它们全部打印到模板中,请创建一个字符串切片并附加到它...
// Create s as a slice of string
var s []string
for _, quote := range quotes {
// append each result from loop to slice
s = append(s, fmt.Sprintf("%v: bid $%.02f (%v shares), ask $%.02f (%v shares) [as of %v]\n",
quote.Symbol, quote.BidPrice, quote.BidSize,
quote.AskPrice, quote.AskSize, quote.LastUpdated))
}
这是 html 模板中的输出,它现在包括s切片中的所有值...

TA贡献1796条经验 获得超4个赞
您正在重新定义流程函数中的 s 。
var s string
for _, quote := range quotes {
s = fmt.Sprintf("%v: bid $%.02f (%v shares), ask $%.02f (%v shares) [as of %v]\n",
quote.Symbol, quote.BidPrice, quote.BidSize,
quote.AskPrice, quote.AskSize, quote.LastUpdated)
// ****************REMOVE s:= from here.**********
}
例子:
func main() {
s := ""
items := []int{1}
for _, quote := range items {
s = "1"
fmt.Println(quote)
}
fmt.Println(s)
}
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报