Home > other >  cannot use strings.NewReplacer("#", "o") (type *strings.Replacer) as type string
cannot use strings.NewReplacer("#", "o") (type *strings.Replacer) as type string

Time:10-24

I am learning Go language from "Head First Go" and came across an example in 2nd chapter

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))

}

command-line-arguments ./hello.go:10:6: cannot use strings.NewReplacer("#", "o") (type *strings.Replacer) as type strings.Replacer in assignment

CodePudding user response:

strings.NewReplacer("#", "o") returns the pointer *strings.Replacer. So the line should be

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

Link to the working program : https://play.golang.org/p/h1LOC-OUoJ2

CodePudding user response:

The definition for strings.NewReplacer is func NewReplacer(oldnew ...string) *Replacer. So the function returns a pointer to a Replacer (see the tour for more on pointers).

In the statement var replacer strings.Replacer = strings.NewReplacer("#", "o") you are defining a variable with the type strings.Replacer and then trying to assign a value of type *strings.Replacer to it. As these are two different types the compiler reports an error. The fix is to use the correct type var replacer *strings.Replacer = strings.NewReplacer("#", "o") (playground).

replacer := strings.NewReplacer("#", "o") works OK because when using a short variable declaration the compiler determines the type (*strings.Replacer) for you.

  • Related