如何将函数的结果写入切片中

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

How to write the result of a function in a slice

问题

在这个例子中,一切都正常工作。但是他们没有使用变量a并立即显示它。但是我有一个问题:

package main
import (
    "fmt"
    "strings"
)

func main() {
    str := "fulltext"
    var slice []string
    slice = strings.Split(str , "")

    fmt.Printf("anwer: ", slice)
}

答案中为什么会有多余的字符,例如:

%! (EXTRA [] string =

P.S. 我知道我需要使用append来向切片中添加元素,但是现在我不知道如何在这里应用append。

更新:
现在我得到的答案是:

anwer: %!(EXTRA []string=[f u l l t e x t])

但是我只需要:

[f u l l t e x t]

但是我不知道我应该如何修改我的代码?

英文:

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?

答案1

得分: 2

问题不在于将strings.Split()的返回值分配给局部变量slice,这是完全正确的。

问题在于你使用了fmt.Printf(),它期望一个格式化字符串,并根据该格式化字符串格式化/替换预期的参数。由于你的格式化字符串不包含任何占位符,所以fmt.Printf()调用不需要参数,但你却传递了一个参数,因此它会用额外的字符(一种错误字符串)来表示这个问题。

提供一个有效的格式化字符串,其中指示你将提供一个参数,即一个切片:

fmt.Printf("answer: %v", slice)

这样,输出结果将是:

answer: [f u l l t e x t]

或者你可以使用fmt.Println(),它不需要格式化字符串:

fmt.Println("answer:", slice)

(注意冒号后面没有空格,因为fmt.Println()会在两个值之间添加一个空格,如果其中一个值的类型是string)。

输出结果是相同的。你可以在Go Playground上尝试这些示例。

如果继续使用fmt.Printf(),当参数涉及到string值时,%q占位符通常更有用,因为它会打印带引号的字符串值,更容易发现某些错误(例如不可见字符,或者如果一个string包含空格,那么这将变得明显):

fmt.Printf("answer: %q\n", slice)

这个输出结果是(你可以在Go Playground上尝试):

answer: ["f" "u" "l" "l" "t" "e" "x" "t"]

如果你想要追加一个函数调用的结果,可以这样写:

slice := []string{"initial", "content"}
slice = append(slice, strings.Split(str, "")...)

fmt.Printf("answer: %q\n", slice)

现在的输出结果是(你可以在Go Playground上尝试):

answer: ["initial" "content" "f" "u" "l" "l" "t" "e" "x" "t"]
英文:

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"]

答案2

得分: 0

给printf提供预期的格式,在大多数情况下,%v是可以的。

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "fulltext"
	var slice []string
	slice = strings.Split(str, "")

	fmt.Printf("anwer: %v", slice)
}

更多信息请参阅https://golang.org/pkg/fmt/。

英文:

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.

huangapple
  • 本文由 发表于 2017年7月10日 02:50:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/44999853.html
匿名

发表评论

匿名网友

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

确定