The "generic function or template function" of the Go language

Source: Internet
Author: User
Tags switch case
This is a created article in which the information may have evolved or changed.

First of all know that Golang is not a Java generic function or C + + template function of this syntax, today learned a very useful similar to the generic operation of the syntax, to share with you

The purpose of this is to implement a generic add function, as described in the Add function.

Three add functions are written first


Before unifying the three add functions, learn the use of a simple interface{}, noting that Int,int32,int64 is a different type in SetValue's generic judgments

I believe most of the students here understand that we are going through switch data:=input. (type) to implement the so-called generics, by first using the most general pseudo-code: ADD (A, b) {return a+b}
PS: Here B2 is actually a float64 type
You can also pass pointers
See if there is a problem here, if my Add function is pseudo-code: Add (a,b,c) {return a+b+c}, do I want a switch case nested 3 times? It's too hard to look at this code, so the custom data type can be judged, too.
By customizing Intstruct, float32struct, stringstruct This structure, the code looks much more comfortable.

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.