Three features of object-oriented programming 7

Polymorphism and reflect:

basic introduction:

  Variant (examples) have a variety of forms. The third object-oriented features, in Go, characterized by polymorphic interface implementation. You can follow a unified interface to invoke different implementations. At this interface variables to present different forms.


Getting Started:

In the previous case the interface Usb, Usb usb, both phones can receive variables, and variables can receive a camera, a manifestation of polymorphism Usb Interface feature.

Working method for the preparation // This method receives a Usb interface type variable
// long as it implements the interface Usb (called interfaces implemented Usb refers to an interface implements all the methods declared Usb)
FUNC (Computer C) Working (USB Usb) {/ / usb variables passed in argument, in the end is to determine Phone, or Camera, usb interface variables can reflect the polymorphic characteristics.
  // Start and Stop methods invoked through the usb interface variables
  usb.Start ()
  usb.Stop ()
}

 

Interface reflect Polymorphisms:

1) Multi-modal parameters

  In the previous cases Usb Interface, usb Usb, both phones can receive variables, and variables can receive a camera, a manifestation of polymorphism Usb Interface feature.

2) polymorphism array

  Demonstrates a case: to Usb array, storage structures and Camera Phone structure variables, Phone there is a specific method call (), iterate through the array Usb, if the variable is Phone, in addition to the method calls Usb interface declaration, but also Phone calls require unique method call.

Specific method calls the blue part finished after repeat type assertion.

Remarks:

// declare an interface
of the type Usb interface {
  // declare two methods did not achieve the
  Start ()
  Stop ()
}

type Phone struct {
  name string
}

// let Phone Usb interface implementation
FUNC (the p-Phone) Start () {
  fmt.Println ( "the phone started working ...")
}

FUNC (the p-Phone) Stop () {
  fmt.Println ( "phone stopped working ...")
}

type Camera struct {
  name string
}

// let the camera implements methods Usb Interface
FUNC (c Camera) Start () {
  fmt.Println ( "camera to work ...")
}

FUNC (c Camera) Stop () {
  fmt.Println ( "camera stopped working ...")
}

FUNC main () {

  // define an array usb interface, and can store Phone Camera structure variables
  // here embodied polymorphic array
  var usbArr [. 3] Usb
  usbArr [0] = {Phone "Vivo"}
  usbArr [. 1] = {Phone "Millet "}
  usbArr [2] = {Camera" Samsung "}
  fmt.Println (usbArr)
}

 

Type asserted:

A look at the requirements:

See a code
type Point {struct
  X int
  Y int
}

main FUNC () {
  var interface {a}
  var = Point Point Point {1,2}
  a = OK Point //
  // how a variable is assigned to a Point?
  Point b var
  b = A // can it? ==> error must be b = a. (Point) type assertion
  fmt.Println (B)
}

b = a. (Point) is the type assertion indicates determines whether a variable of type Point point, if it is converted into a Point type and assigned to the variable b, otherwise an error.

Demand: How to interface to a variable, the variable assign custom type => lead type assertion.


basic introduction:

Type assertion, since the interface is a general type, do not know the specific type, if you want to turn to a specific type, it is necessary to use type assertions, specifically as follows:


Case:

main FUNC () {
  var {X} interface
  var B = 1.1 float32
  X = B // empty interface that can receive any type
  // x => float32 [usage type assertion]
  Y: X = (float32).
  fmt.Printf ( "type of y is% T value V% ', y, y)
}


Code described above:

During the type of assertion, if the types do not match, it will report panic, and therefore the type assertion, the assertion is to ensure that the type of the original empty interface points.

For example y: = x (float32) written float64 can not because empty interface point is float32 type.


How making assertions, bring detection mechanism, if success is OK, otherwise there will not need to report panic.

Type detection with assertions:

main FUNC () {
  var {X} interface
  var B = 2.1 float32
  X = B // empty interface that can receive any type
  // x => float32 [usage type assertion]

  // Type asserted (with detection)
  // Y, In Flag: = X (float32).
  IF Y, In Flag:. = X (float32); {In Flag
    fmt.Println ( "Convert Success")
    fmt.Printf ( "Y the value of% T type V% ', Y, Y)
  } the else {
    fmt.Println ( "Convert Fail")
  }
  fmt.Println ( "continue ~")
}


Best Practice 1 type of assertion:

Make improvements in front of Usb Interface Case:

  Phone structure to increase a specific method call (), is received by the interface when Usb Phone variables, also need to call the call method.

// declare an interface
type interface Usb {
  // declares two methods do not achieve
  the Start ()
  the Stop ()
}

type Phone struct {
  name string
}

// let Phone Usb interface implementation
FUNC (the p-Phone) Start () {
  fmt.Println ( "the phone started working ...")
}

FUNC (the p-Phone) Stop () {
  fmt.Println ( "phone stopped working ...")
}

FUNC (P Phone) Call () {
  fmt.Println ( "phone call ..")
}

type Camera struct {
  name string
}

// let the camera implements methods Usb Interface
FUNC (c Camera) Start () {
  fmt.Println ( "camera to work ...")
}

FUNC (c Camera) Stop () {
  fmt.Println ( "camera stopped working ...")
}

type Computer struct {

}

FUNC (Computer Computer) Working (usb Usb) {
  usb.Start ()
  // if usb Phone structure is a pointer to a variable, you also need to call the Call method.
  // ... type assertion [Note Experience !!!]
  IF A, OK: = USB (Phone); {OK.
    A.Call ()
  }
  usb.Stop ()
}

func main() {

  // define an array usb interface, and can store Phone Camera structure variables
  // here embodied polymorphic array
  var usbArr [. 3] Usb
  usbArr [0] = {Phone "Vivo"}
  usbArr [. 1] = {Phone "Millet "}
  usbArr [2] = {Camera" Samsung "}

  //遍历usbArr
  var computer Computer
  for _, v := range usbArr{
    computer.Working(v)
    fmt.Println()
  }
  fmt.Println(usbArr)
}


Best Practices type of assertion 2:

// write a function to be determined what type of input parameter
func TypeJudge (items ... interface {} ) {// This function can represent any type of receiving a plurality of arguments
  for i, x: = range items {
    . switch x (type) {// this is a key type, fixed wording
      Case bool:
        fmt.Printf ( "% d parameter is of type bool value V% \ n-",. 1 + I, X)
      Case float32:
        fmt.Printf ( "% d of parameter is float32 type, value V% \ n-",. 1 + I, X)
      Case float64:
        fmt.Printf ( "% d of parameter is float64 type, is% V \ n-",. 1 + I, X)
      Case int, Int32, Int64:
        fmt.Printf ("% d parameter is of type integer, value V% \ n-",. 1 + I, X)
      Case String:
        FMT .Printf ( "% d argument of type string, the value is% v \ n",. 1 + I, X)
      default:
        fmt.Printf ( "% d of uncertain parameter is the type, the value is% v \ n ", i + 1,x)
    }
  }
}

func main() {

  var n1 float32 = 1.1
  var n2 float64 = 2.3
  var n3 int64 = 30
  var name string = "tom"
  address := "北京"
  n4 := 300

  TypeJudge(n1, n2, n3, name, address, n4)
}

The result is:

Best Practice Type assertion of 3:

On the basis of the previous code, and type of increase is determined Student * Student type

package main
import (
  "fmt"

)

type Student struct {

}

// write a function to be determined what type of input parameter
FUNC TypeJudge (interface items {...}) {
  for I, X: = {Range items
    . Switch X (type) {// this is a key type fixed wording
      Case bool:
        fmt.Printf ( "% d parameter is of type bool value V% \ n-",. 1 + I, X)
      Case float32:
        fmt.Printf ( "% d of type parameter is float32 , value V% \ n-",. 1 + I, X)
      Case float64:
        fmt.Printf ("% d of parameter is float64 type, value V% \ n-",. 1 + I, X)
      Case int, Int32 , Int64:
        fmt.Printf ( "% d parameter is of type integer, value V% \ n-",. 1 + I, X)
      Case string:
        fmt.Printf ( "% d argument of type string, the value is % v \ n ", i + 1, X)
      Case Student:
        fmt.Printf ("% d of Student type parameter is, the value is% v \ n ", i + 1,x)
      case *Student :
        fmt.Printf ( "% d of * Student parameter is type, value% v \ n-",. 1 + I, X)
      default:
        fmt.Printf ( "% d of uncertain parameter is the type, the value is% v \ n-",. 1 + I, X)
    }
  }
}

func main() {

  var n1 float32 = 1.1
  var n2 float64 = 2.3
  var n3 int64 = 30
  var name string = "tom"
  address := "北京"
  n4 := 300

  stu1 := Student{}
  stu2 := &Student{}

  TypeJudge(n1, n2, n3, name, address, n4, stu1, stu2)
}

Guess you like

Origin www.cnblogs.com/green-frog-2019/p/11415543.html