为了账号安全,请及时绑定邮箱和手机立即绑定

不能在赋值中使用 strings.NewReplacer("#", "o")

不能在赋值中使用 strings.NewReplacer("#", "o")

Go
萧十郎 2022-10-10 15:50:37
我正在从“Head First Go”学习 Go 语言,并在第 2 章遇到了一个示例package mainimport (    "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) 作为类型 strings.Replacer 赋值
查看完整描述

2 回答

?
收到一只叮咚

TA贡献1821条经验 获得超5个赞

strings.NewReplacer("#", "o")返回指针*strings.Replacer。所以这条线应该是

var replacer *strings.Replacer = strings.NewReplacer("#", "o")

链接到工作程序: https: //play.golang.org/p/h1LOC-OUoJ2


查看完整回答
反对 回复 2022-10-10
?
慕田峪9158850

TA贡献1794条经验 获得超8个赞

的定义strings.NewReplacerfunc NewReplacer(oldnew ...string) *Replacer。因此该函数返回一个指向Replacer指针(有关指针的更多信息,请参见教程)。

在语句中var replacer strings.Replacer = strings.NewReplacer("#", "o"),您正在定义一个具有类型的变量,strings.Replacer然后尝试为其分配一个类型的值*strings.Replacer。由于这是两种不同的类型,编译器会报告错误。解决方法是使用正确的类型var replacer *strings.Replacer = strings.NewReplacer("#", "o")playground)。

replacer := strings.NewReplacer("#", "o")工作正常,因为当使用短变量声明时,编译器会*strings.Replacer为您确定类型 ( )。


查看完整回答
反对 回复 2022-10-10
  • 2 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号