Get the App
SLTechnology News&Howtos  ›  Development  › 

How to transform Interface objects in golang

Shulou Source: shulou.com Published: 2022-06-03 07:06:39 10月02日 Update

This article mainly introduces how to transform the interface object in golang. It is very detailed and has a certain reference value. Friends who are interested must finish it!

There are two ways to transform interface objects:

1. Method 1: instance,ok:= interface object. (actual type)

If the interface object is the corresponding actual type, then instance is the transformed object, and the value of ok is true.

Cooperate with if...else if... Use

two。 Method 2:

Interface object. (type)

Use with switch...case statement

Example:

Package main import ("fmt"math") type shape interface {perimeter () int area () int} type rectangle struct {an int / / long b int / / wide} func (r rectangle) perimeter () int {return (r.a + r.b) * 2} func (r rectangle) area () int {return r.a * r.b} type circle struct {radios int} func (c circle) perimeter () int { Return 2 * c.radios * int (math.Round (math.Pi))} func (c circle) area () int {return int (math.Pow (float64 (c.radios)) 2) * math.Pi)} func getType (s shape) {if I, ok: = s. (rectangle) Ok {fmt.Printf ("length of rectangle:% d, width of rectangle:% d\ n", i.a, i.b)} else if i, ok: = s. (circle) Ok {fmt.Printf ("radius of the circle is:% d\ n", i.radios)}} func getType2 (s shape) {switch I: = s. (type) {case rectangle: fmt.Printf ("the length of the rectangle:% d, the width of the rectangle is:% d\ n", i.a, i.b) case circle: fmt.Printf ("the radius of the circle is:% d\ n" I.radios)} func getResult (s shape) {fmt.Printf ("the perimeter of the graph is:% d, the area of the graph is:% d\ n", s.perimeter (), s.area ())} func main () {r: = rectangle {a: 10, b: 20} getType (r) getResult (r) c: = circle {radios: 5} getType2 (c) getResult (c)}

The above example uses mode 1. If you want to use mode 2, you can change the getType () function to:

Func getType (s shape) {switch I: = s. (type) {case rectangle: fmt.Printf ("length of the graph:% .2f, width of the graph:% .2f\ n", i.a, i.b) case triangle: fmt.Printf ("the first edge of the graph:% .2f, the second edge of the graph:% .2f The third edge of the graph:% .2f\ n ", i.arect i.bscoii.c) case circular: fmt.Printf (" Radius of the graph:% .2f\ n ", i.radius)}} above is all the content of this article" how to transform interface objects in golang ". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Graphics objects interfaces methods rectangles s.s. radius i.b content circle reality article type r.aforce r.b three values examples interests functions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology Shulou Information Xiaomi MySQL