【发布时间】:2021-12-10 01:00:19
【问题描述】:
我正在从“Head First Go”学习 Go 语言,并在第 2 章中遇到了一个示例
package main
import (
"fmt"
"strings"
)
func main(){
var broken string = "Go# R#cks!"
//**Below line doesn't work, getting error as shown after the program :**-
var replacer strings.Replacer = strings.NewReplacer("#", "o")
// Whereas this line works perfectly
replacer := strings.NewReplacer("#", "o")
var fixed string = replacer.Replace(broken)
fmt.Println(replacer.Replace(fixed))
}
命令行参数 ./hello.go:10:6: 不能使用 strings.NewReplacer("#", "o") (type *strings.Replacer) as type 赋值中的strings.Replacer
【问题讨论】:
-
如错误所述,应用程序尝试将
*strings.Replacer分配给strings.Replacer。通过将变量声明为指针来修复:var replacer *strings.Replacer = strings.NewReplacer("#", "o")