是否可以在Golang中将a转换string为io.Writer类型?
我将使用此字符串,fmt.Fprintf()但我无法转换类型.
我已经阅读了关于“ https://github.com/golang/go/issues/25484 ”关于从[]byteto 的无复制转换string。
我想知道是否有办法将字符串转换为没有内存复制的字节片?
我正在编写一个处理 terra 字节数据的程序,如果每个字符串在内存中复制两次,则会减慢进度。而且我不关心可变/不安全,只关心内部使用,我只需要尽可能快的速度。
例子:
var s string
// some processing on s, for some reasons, I must use string here
// ...
// then output to a writer
gzipWriter.Write([]byte(s)) // !!! Here I want to avoid the memory copy, no WriteString
Run Code Online (Sandbox Code Playgroud)
所以问题是:有没有办法防止内存复制?我知道也许我需要 unsafe 包,但我不知道如何。我已经搜索了一段时间,直到现在还没有答案,SO 也没有显示相关的答案有效。
我很好奇为什么Golang没有提供[]byte(*string)方法.从性能的角度来看,不会[]byte(string)复制输入参数并增加更多的成本(虽然这看起来很奇怪,因为字符串是不可变的,为什么要复制它们)?
我是Go的新手,非常感谢任何澄清.
我无法理解ResponseWriter语法的一部分。
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}
Run Code Online (Sandbox Code Playgroud)
例如,在go by example 提供的示例中,该area方法由两个实现geometry接口的对象实现。
的http.ResponseWriter是一个接口,其能够Write,除其他事项。
我写了以下内容来测试 w ResponseWriter
func sendData(w http.ResponseWriter, r *http.Request) {
fmt.Println(w)
}
func main() {
http.HandleFunc("/", sendData)
http.ListenAndServe(":8081", nil)
}
Run Code Online (Sandbox Code Playgroud)
浏览器返回结果为空
在执行代码的终端中,我获得了以下标准输出:
&{0xc00009ebe0 0xc0000e8100 {} 0x112a550 false false false false 0xc00006c500 {0xc0000d40e0 map[] false false} map[] false 0 -1 0 false false [] 0 [0 0 0 0 0 0 …Run Code Online (Sandbox Code Playgroud)