Passing string argument in golang

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

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

huangapple
  • 本文由 发表于 2017年3月28日 13:13:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/43061069.html
匿名

发表评论

匿名网友

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

确定