Golang之interface(多態,類型斷言)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

多態用法

package main//一種事物的多種形態,都可以按照統一的介面進行操作//多態import (    "fmt"    "math/rand"    "sort")type Student struct {    Name     string    Id       string    Age      int    sortType int}type Book struct {    Name   string    Author string}//切片預設傳地址type StudentArray []Studentfunc (p StudentArray) Len() int {    return len(p)}func (p StudentArray) Less(i, j int) bool {    return p[i].Name < p[j].Name}func (p StudentArray) Swap(i, j int) {    p[i], p[j] = p[j], p[i]}func main() {    var stus StudentArray    for i := 0; i < 10; i++ {        stu := Student{            Name: fmt.Sprintf("stu%d", rand.Intn(100)),            Id:   fmt.Sprintf("110%d", rand.Int()),            Age:  rand.Intn(100),        }        stus = append(stus, stu)    }    for _, v := range stus {        fmt.Println(v)    }    fmt.Println("\n\n")    sort.Sort(stus)    for _, v := range stus {        fmt.Println(v)    }}

 介面嵌套

package mainimport "fmt"//介面嵌套 一個介面可以嵌套在另外的介面type Reader interface {    Read()}type Writer interface {    Write()}type ReadWriter interface {    Reader    Writer}type File struct {}func (f *File) Read() {    fmt.Println("read data")}func (f *File) Write() {    fmt.Print("write data")}func Test(rw ReadWriter) {    rw.Read()    rw.Write()}func main() {    var f File    Test(&f)}

 類型斷言

package mainimport "fmt"type Student struct {    Name string    Sex  string}//類型斷言//一個判斷傳入參數類型的函數func just(items ...interface{}) {    for index, v := range items {        switch v.(type) {        case bool:            fmt.Printf("%d params is bool,value is %v\n", index, v)        case int, int64, int32:            fmt.Printf("%d params is int,value is %v\n", index, v)        case float32, float64:            fmt.Printf("%d params is float,value is %v\n", index, v)        case string:            fmt.Printf("%d params is string,value is %v\n", index, v)        case Student:            fmt.Printf("%d params student,value is %v\n", index, v)        case *Student:            fmt.Printf("%d params *student,value is %v\n", index, v)        }    }}func main() {    var b Student = Student{        Name: "stu01",        Sex:  "female",    }    just(28, 8.2, "this is a test", b, &b)}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.