Vijay
Vijay

Reputation: 588

Passing string argument in golang

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

Upvotes: 3

Views: 28228

Answers (1)

RaviTezu
RaviTezu

Reputation: 3125

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

Upvotes: 13

Related Questions