【发布时间】:2018-12-08 21:31:52
【问题描述】:
这是我的第一篇文章,所以请放轻松。 :) ...我非常熟悉许多传统的编程语言,但我是 Go 新手,无法理解切片和范围的使用。下面的程序代码和 cmets 说明了我的惊愕。谢谢!
package main
import (
"fmt"
"time"
)
type myStruct struct {
Name string
Count int
}
写了我自己的 Mod 函数,因为我在 Go 库中找不到。
func modMe(mod int, value int) int {
var m int
var ret int
m = value / mod
ret = value - m*mod
return ret
}
func main() {
mod := 4
cnt := 16
fmt.Printf("Record mod is %d\r\n", mod)
声明一个结构数组并添加一些记录
chartRecords := []myStruct{}
for i := 0; i<=cnt ;i++ {
n := myStruct{Count: i, Name: fmt.Sprintf("Joe%2d", i)} //Load some data
chartRecords = append(chartRecords,n)
}
加载数据会产生我期望的输出
fmt.Printf("======ORIGINAL LOADED VALUES========\r\n")
i := 0
for _, elem := range chartRecords {
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out original values in the range
i = i + 1
}
现在我修改这些值并打印它们以查看它们是否已修改。这看起来符合预期。
fmt.Printf("======MODIFIED VALUES EXPECTED========\r\n")
i = 0
for _, elem := range chartRecords { //looping thru the range of the data records
mm := modMe(mod, i) //modMe is my function to return the Mod of a number based on moduls 'mod'
elem.Count = mm //assigning the new mod value to Count
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out this elem.Count element in the range
i = i + 1
}
现在我只需再次遍历相同的范围并打印出相同的内容。 但输出显示原始值。 我不明白为什么会这样。我猜它与切片和添加值有关,而不是替换值。
fmt.Printf("======CHECK AGAIN AND VALUES ARE BACK TO ORIGINAL========\r\n") //Now lets loop through the same range
i = 0
for _, elem := range chartRecords {
fmt.Printf("No: %2d | Count: %2d | Name = %s\r\n", i, elem.Count, elem.Name) //Print out this elem.Count element in the range
i = i + 1
} //But this output shows the original values WHY??
time.Sleep(60 * time.Second)
}
输出看起来像这样... Screenshot Output
提前感谢您的建议。
【问题讨论】:
-
供以后参考,Go 中的模运算符是
%: play.golang.org/p/45J5pu5Ca4b