Go basics: interface-related

Source: Internet
Author: User

Interface related

Package Main

Import ("FMT" "math")

Interface that defines the method

The value of the interface type must implement the method defined inside the

Type Abser interface{Abs () float64}

Type Myfloat float64

Type Vertex struct{X, Y float64}

Myfloat Implementing ABS Method

Func (f myfloat) Abs () float64 {

If f < 0{return float64 (-f)} return Float64 (f)}

*vertex Implementing ABS Method

Func (v *vertex) Abs () float64

{return math. SQRT (v.x*v.x + v.y*v.y)

}

Func describe (i interface{})

{FMT. Printf ("%v,%t\n", I, I)}

Func Main ()

{var A, B abser

F: = Myfloat (-math. SQRT2)

Fmt. Println ("======f=", F)

V: = vertex{3,4}

A = f fmt. Println ("======a.abs=", A.abs ())

b = &v FMT. Println ("======b.abs=", B.abs ())

Null interface, no method is developed to implement, can accept any type

var emptyinterface interface{}

Describe (emptyinterface)

Emptyinterface = 12

Describe (emptyinterface)

Emptyinterface = "Wolfan"

Describe (emptyinterface)

}

Go basics: interface-related

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.