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

我正在从“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) 作为类型 strings.Replacer 赋值


萧十郎
浏览 138回答 2
2回答

收到一只叮咚

strings.NewReplacer("#", "o")返回指针*strings.Replacer。所以这条线应该是var replacer *strings.Replacer = strings.NewReplacer("#", "o")链接到工作程序: https: //play.golang.org/p/h1LOC-OUoJ2

慕田峪9158850

的定义strings.NewReplacer是func 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为您确定类型 ( )。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go