I have a code where I need to perform several replaces
and for this I did the following:
exemplo := "Olá, meu nome é xpto, na verdade xpto da silva xpto"
formated := strings.Replace(exemplo, "xpto", "Fulano")
formated := strings.Replace(formated, "Olá", "oi")
fmt.Println(formated)
To try to make it more "friendly" I decided to create a variable of type string
that would allow me to use a chained "replace" method, which would look like this:
exemplo := "Olá, meu nome é xpto, na verdade xpto da silva xpto"
formated := custom(exemplo).replace("xpto", "fulano").replace("olá", "oi")
For this I did:
type custom string
func (c *custom) replace(old, new string) custom {
content := string(*c)
return custom(strings.Replace(content, old, new, -1))
}
func main() {
text := custom("Olá, nome, Olá, nome")
fmt.Println(text.replace("Olá", "oi").replace("nome", "nombre"))
}
When executing the code with only 1 replace
it executes successfully, but if I try to chain another replace
as in the example above I get the error that can not access the pointer nor the address of text.replace("Olá", "oi")
, I believe this error is generated because when I return the "custom" in replace
no memory address is assigned to it.
can not call pointer method on text.replace ("Hi", "hi")
can not take the address of text.replace ("Hello", "hi")
I have tried to assign the return of replace
to a variable to generate a memory address:
func (c *custom) replace(old, new string) *custom {
content := string(*c)
formated := custom(strings.Replace(content, old, new, -1))
return &formated
}
But in this way, Println
in main
will display the address, not the value.
How can I use the value returned from a function in a threaded method?