【问题标题】:cannot use strings.NewReplacer("#", "o") (type *strings.Replacer) as type strings.Replacer in assignment不能在赋值中使用 strings.NewReplacer("#", "o") (type *strings.Replacer) 作为类型 strings.Replacer
【发布时间】: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")

标签: go types


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    strings.NewReplacer 的定义是func NewReplacer(oldnew ...string) *Replacer。因此,该函数将 pointer 返回到 Replacer(有关指针的更多信息,请参阅 the tour)。

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

    replacer := strings.NewReplacer("#", "o") 可以正常工作,因为在使用 short variable declaration 时,编译器会为您确定类型 (*strings.Replacer)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2018-06-28
      • 1970-01-01
      • 2016-03-16
      • 2017-10-19
      • 1970-01-01
      • 2018-05-10
      相关资源
      最近更新 更多