自定义类型和原始类型之间的区别

问题描述:

I have a quick doubt about Go types.

type mystr string
var s1 mystr = "abc"
var s2 string = "abc"

Here s1 always takes string type which is similar to s2. My question is, why defining such types are allowed (which are of primitive types) in Go. When I can't even compare s1 to s2

if s1 == s2 // compilation error

What can be the use case to such scenario?

我对Go类型存有疑问。 p>

  type  mystr string 
var s1 mystr =“ abc” 
var s2 string =“ abc” 
  code>  pre> 
 
 

此处s1始终采用类似于s2的字符串类型。 我的问题是,为什么在Go中允许定义这样的 types em>(属于原始类型)。 当我什至无法比较s1和s2 p>

 如果s1 == s2 //编译错误
  code>  pre> 
 
 

这种情况下的用例是什么? p> div>

It is similar to extension methods in other programming languages. You can add your own behavior to your type (and cannot in standard type):

type MyStr string

func (s MyStr) Length() int {
    return len(string(s))
}

func main() {
    s := MyStr("hello")
    fmt.Println(s.Length())
}