英文:
Passing string argument in golang
问题
刚开始学习Go语言,对基本函数调用有些困惑:
fileContentBytes := ioutil.ReadFile("serverList.txt")
fileContent := string(fileContentBytes)
serverList := strings.Split(fileContent, "\n")
for _, server := range serverList {
fmt.Println("sending", server)
processServer(server)
}
func processServer(s string) {
fmt.Println(s, " : started processing")
}
输出结果:
sending server1
: started processing
sending server2
: started processing
sending server3
server3: started processing
在上述代码中,我能够打印出数组的所有元素,但是只有最后一个元素能够正确传递给函数processServer
。
我做错了什么?
Go版本:1.8
操作系统:Windows 7 x64
英文:
just starting with Go and having trouble with basic function call:
fileContentBytes := ioutil.ReadFile("serverList.txt")
fileContent := string(fileContentBytes)
serverList := strings.Split(fileContent,"\n")
/*
serverList:
server1,
server2,
server3
*/
for _,server := range serverList {
fmt.Println("sending ", server)
processServer(server)
}
func processServer(s string) {
fmt.Println(s, " : started processing")
}
Output:
sending server1
: started processing
sending server2
: started processing
sending server3
server3: started processing
In the above code from the for loop I am able to print all the elements of array but only the last element gets passed properly to the function processServer
.
What am I doing wrong?
Go Version: 1.8
OS: Windows 7 x64
答案1
得分: 12
请提供定义serverList
变量的代码。
或者,您可以使用以下代码片段:
package main
import (
"fmt"
)
func processServer(s string) {
fmt.Println(s, " : started processing")
}
func main() {
serverList := [...]string{"server1","server2","server3"}
for _,server := range serverList {
fmt.Println("sending ", server)
processServer(server)
}
}
您可以在此处运行脚本:https://play.golang.org/p/EL9RgIO67n
英文:
Can you please provide the code, which defines the serverList
variable?
Or else, you can use the below snippet:
package main
import (
"fmt"
)
func processServer(s string) {
fmt.Println(s, " : started processing")
}
func main() {
serverList := [...]string{"server1","server2","server3"}
for _,server := range serverList {
fmt.Println("sending ", server)
processServer(server)
}
}
You can run the script here: https://play.golang.org/p/EL9RgIO67n
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论