In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use interface in Golang". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use interface in Golang.
Omnipotent interface
In Java and other languages, interface is a writing specification, but in golang, interface is also a value, which can be passed like a value. And at its bottom, it is actually a tuple of values and types.
Here let's take a look at an example from the official golang documentation:
Package mainimport ("fmt"math") type I interface {M ()} type T struct {S string} func (t * T) M () {fmt.Println (t.S)} type F float64func (f F) M () {fmt.Println (f)} func main () {var i I i = & T {"Hello"} describe (I) i.M () I = F (math.Pi) describe (I) i.M ()} func describe (I) {fmt.Printf ("(% v)) % T)\ n ", I, I)}
A method called describe is defined in the above code, in which we output two values, one corresponding to interface I and the other to the type of interface I.
You can see that the interface stores both the information of the instance of the corresponding structure and the type of the structure. So interface can be understood as a special type.
In fact, it is true that we can think of interface as a universal data type that can accept values of any type. Let's take a look at the following usage:
Var A1 interface {} = 1var a2 interface {} = "abc" list: = make ([] interface {}, 0) list = append (list, A1) list = append (list, a2) fmt.Println (list)
In the code, we create a slice of type interface {}, which can receive values and instances of any type. In addition, we can also accept the value of any structure with the type interface {}. There may be some confusion here, but it's easy to figure it out. Interface represents a type that can receive values of any type that implements the method specified in interface. When we define inteface {}, we actually define an empty interface, which is equivalent to an empty interface that does not need to implement any method, so any type can accept it, which is why it becomes a universal type.
Of course we have no problem receiving it, but the question is, how do we use these values of type interface?
One way is that we can determine the variable type of an interface. The method of judgment is very simple, we use the method of. (type) after the variable of interface. It is the same as map's key value judgment, which returns a value and a tag of type bool. We can judge whether this type is correct by this mark.
If v, ok: = A1. (int); ok {fmt.Println (v)}
It is also possible to use switch if there are many types:
Switch v: = I. (type) {case int: fmt.Println ("int") case string: fmt.Println ("string")} null nil
The null value of the interface type is nil, which means the same thing as None in Python, indicating that a pointer points to null. If we call a method on a null pointer in Java or other languages, it will trigger NullPointerMethodError, that is, an error with the null pointer. This is also the most common mistake that we beginners encounter in programming, often because we forget to initialize the declaration.
But not in golang, even nil can call the method of interface. For example:
Type T struct {S string} func (t * T) M () {fmt.Println (t.S)} func main () {var i I var t * T I = t I.M ()}
We assigned t to I, but the problem is that t is not initialized, so it is a nil, so our I will also be a nil. We call the M method on nil, in which we print the local variable S of t. Because t is now a nil, it does not have this variable, so it raises an invalid memory address or nil pointer derefernce error, that is, an error addressing the null pointer.
To solve this error, it is actually very simple, we can judge t in the M method, and if we find that t is a nil, then we skip the logic of execution. When we change the M function to this, the null pointer problem will not be triggered.
Func (t * T) M () {if t = = nil {fmt.Println ("nil") return} fmt.Println (t.s)}
The problem of nil triggering exception is also one of the problems often encountered by beginners, which requires us to remember to judge whether the calling object is nil or not when implementing the method in the body of the structure, so as to avoid unnecessary problems.
Type selection of assignment
We all know that golang implements polymorphism through interface. As long as we implement the function defined in interface, we can assign the corresponding instance to this interface type.
This seems to be no problem, but there will still be a little bit of a problem in the actual implementation. For example, we have a piece of code like this:
Type Integer inttype Operation interface {Less (b Integer) bool Add (b Integer)} func (an Integer) Less (b Integer) bool {return a < b} func (a * Integer) Add (b Integer) {* a + = b}
This code is very simple. We define an interface for Operation and implement two methods of type Integer. On the face of it, everything looks fine, but there is one detail. Less and Add are of different types. We do not need to modify the original value of the Less method, so we pass in the value of Integer, while the Add method, we need to modify the original value, so the type we pass in is the pointer of Integer.
So the question is, the types of these two methods are different, can we still assign its value to the interface of Operation? If possible, should we pass a value or a pointer? Which of the second or third lines of the following code is correct?
Var an Integer = 1var b Operation = & avar b Operation = a
The answer to the second line is correct, and the reason is simple, because when we pass in the pointer, golang's compiler automatically generates a new Less method. In this converted method, the original method is called, which is equivalent to a layer of transfer.
Func (a * Integer) Less (b Integer) bool {return (* a) .less (b)}
How about the other way around? We also write the code:
Func (an Integer) Add (b Integer) {(& a) .add (b)}
Obviously, this will not work, because after the function is executed, it can only change the value of the parameter an in the Add method, but there is no way to change the original value. This didn't match what we wanted, so golang didn't choose this strategy.
Thank you for your reading, the above is the content of "how to use interface in Golang". After the study of this article, I believe you have a deeper understanding of how to use interface in Golang, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.