Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Golang是否将字符串转换为io.Writer?_String_Go_Writer - Fatal编程技术网

String Golang是否将字符串转换为io.Writer?

String Golang是否将字符串转换为io.Writer?,string,go,writer,String,Go,Writer,是否可以在Golang中将字符串转换为io.Writer类型 我将在fmt.Fprintf()中使用此字符串,但我无法转换类型。您不能写入字符串,Go中的字符串是不可变的 最好的替代方法是and,因为Go 1.10是更快的类型:它们的实现是为了让您可以写入它们,您可以通过and以字符串的形式获取它们的内容,或者通过and以字节片的形式获取它们的内容 如果使用以下内容创建缓冲区,还可以使用字符串作为缓冲区的初始内容: 输出(在上尝试): 如果要附加string类型的变量(或string类型的任何值

是否可以在Golang中将
字符串
转换为
io.Writer
类型


我将在
fmt.Fprintf()
中使用此字符串,但我无法转换类型。

您不能写入
字符串,Go中的
字符串是不可变的

最好的替代方法是and,因为Go 1.10是更快的类型:它们的实现是为了让您可以写入它们,您可以通过and以
字符串
的形式获取它们的内容,或者通过and以字节片的形式获取它们的内容

如果使用以下内容创建缓冲区,还可以使用
字符串作为缓冲区的初始内容:

输出(在上尝试):

如果要附加
string
类型的变量(或
string
类型的任何值),只需使用(或):

或:

还请注意,如果您只想连接2个
字符串
s,则无需创建缓冲区并使用,只需使用
+
运算符即可连接它们:

s := "Hello"
s2 := ", World!"

s3 := s + s2  // "Hello, World!"
另见:


它可能也很有趣:

使用实现
Write()
方法的
bytes.Buffer

import "bytes"

writer := bytes.NewBufferString("your string")

我看到另一个答案提到了
strings.Builder
,但我没有看到一个例子。所以 给你:

package main

import (
   "fmt"
   "strings"
)

func main() {
   b := new(strings.Builder)
   fmt.Fprint(b, "south north")
   println(b.String())
}

请给我一个例子,说明如何在函数fmt.Fprintf()中使用字符串类型的变量:为什么不使用fmt.Sprintf()?
fmt.Fprint(buf, s2)
s := "Hello"
s2 := ", World!"

s3 := s + s2  // "Hello, World!"
import "bytes"

writer := bytes.NewBufferString("your string")
package main

import (
   "fmt"
   "strings"
)

func main() {
   b := new(strings.Builder)
   fmt.Fprint(b, "south north")
   println(b.String())
}