Golang Interface Interface Comprehensive understanding (i)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

There is three kinds of time:the the future is late, and now it's flying like an arrow. The past would never stand still.

The pace of time has three kinds: the future is long overdue, now like an arrow flies, the past will never stand still.

What is interface

In object-oriented programming, it can be said that the "interface defines the behavior of an object", then the specific implementation behavior depends on the object.

In go, an interface is a set of method signatures . When a type provides a definition for all the methods in an interface, it is called implementing the interface. It is very similar to OOP. The interface specifies the methods that the type should have, and the type determines how these methods are implemented.

Create and Implement Interface

In Golang, as long as the interface definition is implemented, (JAVA implement) implements the interface

package mainimport (      "fmt")//定义interface type VowelsFinder interface {      FindVowels() []rune}type MyString string//实现接口func (ms MyString) FindVowels() []rune {      var vowels []rune    for _, rune := range ms {        if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {            vowels = append(vowels, rune)        }    }    return vowels}func main() {      name := MyString("Sam Anderson") // 类型转换    var v VowelsFinder // 定义一个接口类型的变量    v = name     fmt.Printf("Vowels are %c", v.FindVowels())}

Actual use of the interface

Why is it actually used? If we were in the code above,

fmt.Printf("Vowels are %c", v.FindVowels())

Replaced by

fmt.Printf("Vowels are %c", name.FindVowels())

The same output as the program, without using the interface we defined. (v variable Delete definition)

Below we explain through the case:

Suppose a company has two employees, an ordinary employee and a senior employee, but the basic salary is the same, and the senior employee takes more bonuses. Calculates the total cost of the company for the employee.

package mainimport ("fmt")// 薪资计算器接口type SalaryCalculator interface {CalculateSalary() int}// 普通挖掘机员工type Contract struct {empId  intbasicpay int}// 有蓝翔技校证的员工type Permanent struct {empId  intbasicpay intjj int // 奖金}func (p Permanent) CalculateSalary() int {return p.basicpay + p.jj}func (c Contract) CalculateSalary() int {return c.basicpay}// 总开支func totalExpense(s []SalaryCalculator) {expense := 0for _, v := range s {expense = expense + v.CalculateSalary()}fmt.Printf("总开支 $%d", expense)}func main() {pemp1 := Permanent{1,3000,10000}pemp2 := Permanent{2, 3000, 20000}cemp1 := Contract{3, 3000}employees := []SalaryCalculator{pemp1, pemp2, cemp1}totalExpense(employees)}

Experience the beauty of using the interface!

Internal performance of the interface

An interface can be thought of as being represented internally by a tuple (type, value). Type is the underlying concrete type of the interface, and value is a specific type.

package mainimport ("fmt")type Test interface {Tester()}type MyFloat float64func (m MyFloat) Tester() {fmt.Println(m)}func describe(t Test) {fmt.Printf("Interface 类型 %T ,  值: %v\n", t, t)}func main() {var t Testf := MyFloat(89.7)t = fdescribe(t)t.Tester()}

Output:

Interface type Main. Myfloat, Value: 89.7
89.7

Null interface

An interface with 0 methods is called an empty interface. It is represented as interface {}. Because there are 0 methods for an empty interface, all types implement an empty interface.

package mainimport ("fmt")func describe(i interface{}) {fmt.Printf("Type = %T, value = %v\n", i, i)}func main() {     // 任何类型的变量传入都可以s := "Hello World"i := 55strt := struct {name string}{name: "Naveen R",}describe(s)describe(i)describe(strt)}

Type assertion

The type assertion is used to extract the underlying value of the interface, syntax:I. (T)

package mainimport("fmt")func assert(i interface{}){    s:= i.(int)    fmt.Println(s)}func main(){  var s interface{} = 55  assert(s)}

The program prints an int value, but if we assign a string to the s variable, the program will panic.

Therefore, the above program can be rewritten as:

package mainimport (      "fmt")func assert(i interface{}) {      v, ok := i.(int)    fmt.Println(v, ok)}func main() {      var s interface{} = 56    assert(s)    var i interface{} = "Steven Paul"    assert(i)}

If the value of I is of type int, then V is the value of I, OK is true. Otherwise OK is false and the program does not panic.

Type judgment

A type-judged syntax is similar to a type assertion. In the syntax of type assertion I (type), the type literal should be replaced by the type conversion keyword type. Let's see how it works in the program below.

package mainimport (      "fmt")func findType(i interface{}) {      switch i.(type) {    case string:        fmt.Printf("String: %s\n", i.(string))    case int:        fmt.Printf("Int: %d\n", i.(int))    default:        fmt.Printf("Unknown type\n")    }}func main() {      findType("Naveen")    findType(77)    findType(89.98)}

You can also compare a type to an interface. If we have a type and the type implements an interface, you can compare it to the interface it implements.

package mainimport "fmt"type Describer interface {      Describe()}type Person struct {      name string    age  int}func (p Person) Describe() {      fmt.Printf("%s is %d years old", p.name, p.age)}func findType(i interface{}) {      switch v := i.(type) {    case Describer:        v.Describe()    default:        fmt.Printf("unknown type\n")    }}func main() {      findType("Naveen")    p := Person{        name: "Naveen R",        age:  25,    }    findType(p)}

Output:

unknown type  Naveen R is 25 years old  

Finally, leave a small question, guess the output of the following program:

package mainimport "fmt"type Describer interface {      Describe()}type St stringfunc (s St) Describe() {      fmt.Println("被调用le!")}func findType(i interface{}) {      switch v := i.(type) {    case Describer:        v.Describe()    case string:        fmt.Println("String 变量")    default:        fmt.Printf("unknown type\n")    }}func main() {      findType("Naveen")    st := St("我的字符串")    findType(p)}

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.