golang type in common usage

golang, the type is very important keywords, general common usage is to define the structure, interfaces, etc., but there are many other type of usage, met several in the study, this is a brief summary of the next record

  • Definition structure
type Person struct {
    name string
    age int
}

type Mutex struct {}
type OtherMutex Mutex //定义新的类型

func (m *Mutex) Lock(){
    fmt.Println("lock")
}
func (m *Mutex) Unlock(){
    fmt.Println("lock")
}

func main() {
    m := &OtherMutex{} //注意,OtherMutex不具有Lock和Unlock方法
    m.Lock()
}
  • Defined interfaces
type Personer interface{
    ShowName(s string)
}
  • Type Definition
type Myint int  //定义一个新的类型,

//定义一个类型方法
func (m Myint) showValue() {
    fmt.Println("show int", m)
}

func main() {
    var m Myint = 9 //变量声明
    m.showValue()
}

新定义的类型,可以定义方法,
如上例的 showValue()
  • Alias ​​definitions

    And the original definition of the same type, that is an alias alias

type nameMap = map[string]interface{}

func main() {
   m :=make(nameMap)
   m["name"] = "golang"
   fmt.Printf("%v", m)
}

另外别名定义和类型定义有点区别
 
type A int32   //类型定义,生成新的
type B = int32 //别名定义,仅仅是 alias

func main() {
    var a A = 333
    fmt.Println(a)
    var b B = 333
        b = B(a) //a,b属于不同的类型,所以这里需要强制转换
    fmt.Println(b)

}
  • Defined Function type
type cb func(s string)  // 定义一个函数类型

//对函数类型再定义方法
func (f cb) ServerCb() error{
    f("cbb")
    fmt.Println("server cb")
    return nil
}

func main() {
    s :=cb(func( s string){
        fmt.Println("sss", s)
    })
    s.ServerCb()
}

In fact, this definition of the way, and the way to achieve an interface definition is similar to the feeling of this is to make the code more clear, if the statement is too complicated, it does not seem all a mess of this definition.

Well, that's some commonly used type of usage.

Guess you like

Origin www.cnblogs.com/smartrui/p/11425822.html