Reputation: 13
In the example, everything works fine. But they do not use the variable a and immediately display it https://play.golang.org/p/O0XwtQJRej
But I have a problem:
package main
import (
"fmt"
"strings"
)
func main() {
str := "fulltext"
var slice []string
slice = strings.Split(str , "")
fmt.Printf("anwer: ", slice)
}
Whence in the answer there are superfluous characters, for example
%! (EXTRA [] string =
P.S. I know that I need to use append to add elements to the slice, but now I do not understand how to apply append here.
UP: Now I have the answer:
anwer: %!(EXTRA []string=[f u l l t e x t])
But I need just:
[f u l l t e x t]
But I do not understand how I should change my code?
Upvotes: 1
Views: 60
Reputation: 418207
The problem is not with the assignment of the return value of strings.Split()
to the local variable slice
, which is totally fine.
The problem is that you used fmt.Printf()
which expects a format string, and based on that format string it formats / substitutes expected parameters. Since your format string does not contain any verbs, that fmt.Printf()
call expects no parameters, yet you pass it one, so it signals this with those extra characters (kind of error string).
Provide a valid format string where you indicate you will supply 1 parameter, a slice:
fmt.Printf("answer: %v", slice)
With this, the output is:
answer: [f u l l t e x t]
Or alternatively use fmt.Println()
, which does not expect a format string:
fmt.Println("answer:", slice)
(Note that there is no space after the colon, as fmt.Println()
adds a space between 2 values if one of them is of type string
).
Output is the same. Try the examples on the Go Playground.
Staying with fmt.Printf()
, when the parameter involves string
values, the %q
verb is often more useful, as that will print quoted string values, much easier to spot certain mistakes (e.g. invisible characters, or if a string
contains spaces, it will become obvious):
fmt.Printf("answer: %q\n", slice)
Output of this (try it on the Go Playground):
answer: ["f" "u" "l" "l" "t" "e" "x" "t"]
If you'd wanted to append the result of a function call, this is how it could look like:
slice := []string{"initial", "content"}
slice = append(slice, strings.Split(str, "")...)
fmt.Printf("answer: %q\n", slice)
And now the output (try it on the Go Playground):
answer: ["initial" "content" "f" "u" "l" "l" "t" "e" "x" "t"]
Upvotes: 2
Reputation: 4134
Give to printf the expected format, in most cases, %v
is fine.
package main
import (
"fmt"
"strings"
)
func main() {
str := "fulltext"
var slice []string
slice = strings.Split(str, "")
fmt.Printf("anwer: %v", slice)
}
see https://golang.org/pkg/fmt/ for more info.
Upvotes: 0