[Golang] Use cases for "generics" through interface

Source: Internet
Author: User
Tags bool comparable comparison printf

Currently Golang the latest version is 1.9, generics are not supported for the time being.
However, you can implement the "generic programming" effect via interface, as an example of adding/removing elements of the slice type data,
for your reference:

Package main import ("Errors" "FMT") var (err_elem_exists = errors.
    New ("element exits.") err_elem_not_exists = errors.

New ("element not exits."))
    Define slice, support interface{} type//Assume that slice does not support storing the same element type Someslice []interface{}//Initialize Slice instance func newsomeslice () Someslice { Return make (Someslice, 0)}//define an interface for comparison type comparable interface {isequal (a interface{}) bool}//define struct class Type type employee struct {Id int32 Name string}//employee type implements comparable interface Func (EM Employee) isequal (b Inter face{}) bool {if em2, OK: = B. (Employee); ok {return em. Id = = em2. Id} else {return false}}//IsEqual function is used for comparison between various types of Func isequal (A, B interface{}) bool {if CMPA, O K: = A. (comparable); OK {return CMPA. IsEqual (b)} else if CMPB, OK: = B. (comparable); OK {return CMPB.
    IsEqual (a)} else {return a = = b}}//Add element func (ss *someslice) Add (Elem interface{}) to slice error { For _, V: =Range *ss {if isequal (V, elem) {fmt. Printf ("[error]cannot Add the same element:%v\n", Elem) return err_elem_exists}} *ss = AppE nd (*SS, elem) return nil}//Remove elements from slice func (ss *someslice) Remove (elem interface{}) error {for k, V: = Range
                *ss {if isequal (V, elem) {if k = = Len (*ss)-1 {*ss = (*SS) [: K]} else {
            *ss = Append ((*SS) [: K], (*SS) [k+1:] ...) } return nil}} FMT. Printf ("[Error]no such element:%v\n", Elem) return err_elem_not_exists} func main () {//Initialize slice slice: = Newsomeslice ()//add different types of element slice under normal conditions. ADD (5) slice. ADD ("Huahua") slice. ADD (employee{id:123, Name: "Xiaohong"}) slice. ADD (Ten) slice. ADD ("xiaoming") slice. ADD (employee{id:456, Name: "Xiaogang"}) fmt. Println ("After add, current Slice:", Slice)//Added duplicate element Slice. ADD (Ten) slice.
  ADD ("Huahua")  Slice. ADD (employee{id:456, Name: "Xiaogang"}) fmt. PRINTLN ("After invalid ADD, current Slice:", Slice)//delete element Slice normally. Remove (5) slice. Remove ("Huahua") slice. Remove (employee{id:456, Name: "Xiaogang"}) fmt. Println ("After remove, current Slice:", Slice)//delete the element Slice that does not exist. Remove (one) slice. Remove ("somename") slice. Remove (employee{id:789, Name: "Dajiu"}) fmt. PRINTLN ("After invalid Remove, current Slice:", Slice)}

The results of the operation are as follows:

pintai@mg:~/src$ go run tmpl.go after
Add, current Slice: [5 Huahua {123 Xiaohong} xiaoming {456 Xiaogang}]
[Er  Ror]cannot Add the same element:10
[error]cannot Add the same Element:huahua
[error]cannot Add the same element: {456 Xiaogang}
After invalid ADD, current Slice: [5 Huahua {123 Xiaohong} (Xiaoming {456 Xiaogang}] After
Remove, current Slice: [{ 123 Xiaohong} xiaoming]
[error]no such element:11
[error]no such element:somename
[error]no such element : {789 Dajiu} after
invalid Remove, current Slice: [{123 Xiaohong} Xiaoming]

The above example implements a slice that supports different types of elements, adding and removing elements through the Add/remove method.
One of the key methods is isequal, for objects that implement the comparable type use its IsEqual method to compare, and for other types (underlying types) the data is compared directly with = =.

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.