Reputation: 1
I'm trying to return a string array from a function, but it is printing only the last index position value. Here is my code and output.
package main
import (
"fmt"
)
func main() {
myquote := varFunc("Go", "Bunny", "Let's", "Change", "ourself")
fmt.Println("here also:", myquote)
}
func varFunc(s ...string) string {
fmt.Println(s)
fmt.Printf("%T\n", s)
quote := ""
for _, v := range s {
quote = v
fmt.Println("init: ", quote)
}
fmt.Println("is there: ", quote)
return quote
}
Playground: https://play.golang.org/p/jyZDL5oPmcz
My output:
[Go Bunny Let's Change ourself]
[]string
init: Go
init: Bunny
init: Let's
init: Change
init: ourself
is there: ourself
here also: ourself
Program exited.
Upvotes: 0
Views: 192
Reputation: 154
Because you are overwriting the last value with =
operator. If i understood correctly you are trying to print array as a single string. Apply +=
symbol to qoute
and it should work for you.
package main
import (
"fmt"
)
func main() {
myquote := varFunc("Go", "Bunny", "Let's", "Change", "ourself")
fmt.Println("here also:", myquote)
}
func varFunc(s ...string) string {
fmt.Println(s)
fmt.Printf("%T\n", s)
quote := ""
for _, v := range s {
quote += v + " "
fmt.Println("init: ", quote)
}
fmt.Println("is there: ", quote)
return quote
}
Upvotes: 3
Reputation: 3547
Your code returns last value of quote
which is the value on last iteration on string array s
.
If you need to return string array s
- return it. Excuse me for truism.
func varFunc(s ...string) []string {
fmt.Println(s)
fmt.Printf("%T\n", s)
quote := ""
for _, v := range s {
quote = v
fmt.Println("init: ", quote)
}
fmt.Println("is there: ", quote)
return s
}
Upvotes: 2