Hi everyone!
I just came across this taboo in golang - new methods cannot be added to an 
existing type:

package main
import "fmt"

func (s string) print(){
    fmt.Println(s)
}

func main() {
   "hello, world\n".print()
}
------Error------------
./main.go:5: cannot define new methods on non-local type string

So I try to go around it by declaring an inheritance type. But it will thus 
be forbidden from functions already defined for the original type:

package main

import(
    "fmt"
    "strconv"
    ) 

type mystr string

func (s mystr) print(){
    fmt.Println(s)
}

func main() {
   var a mystr ="hello, world\n"
   a.print()
   
   fmt.Println(strconv.ParseInt("78",10, 64))
   
   var x mystr ="452"
   n, _ := strconv.ParseInt(x, 10, 64)
}

------------Error--------------------------
./main.go:21: cannot use x (type mystr) as type string in argument to 
strconv.ParseInt

What made things worse is it is universal, including any type in 
open-source packages from github, to which I cannot add in a new method in 
main.

Is there a way to add methods to an existing type while maintaining all the 
functionalities it already has?

Thanks,
  Zhaoxun

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/ad04a0d8-38e2-4a10-bf35-90698627f170n%40googlegroups.com.

Reply via email to