Confused with type

var now time.Time = time.now()
is valid because time.now() returns a value of type time.Time

But apparently
var replacer strings.Replacer = strings.NewReplacer("#", “o”)
is not correct ! Why ?
I thought the var replacer would be of type strings.Replacer ??

For info I am trying to understand what is explained in the book (paper) “Head first Go” at page 32 & 33.

2 Likes

strings.NewReplacer returns a pointer to a strings.Replacer struct and not the struct itself, so you would need to change your code to
var replacer *strings.Replacer = strings.NewReplacer("#", “o”)
or
replacer := strings.NewReplacer("#", “o”)

3 Likes

Indeed. Thanks.

I should have read the doc !

go doc strings NewReplacer
func NewReplacer(oldnew …string) *Replacer (it returns a pointer)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.