3

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 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I have updated the question with the relevant code
ok, issue solved I added a strings.TrimSpace before calling the processServer function. I guess it was sending the string variable with \r as end of lines in windows will have them as well.
Nice. I am happy that you figured it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.