"Generics" in go?

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang does not support generic markup generics similar to those in Java. Many people are therefore very dissatisfied with the view that no generics add a lot of work. As a result of the complexity of generics support, Golang's design and implementation do not use this generic support as an urgent need to add features. But, if there is no generics, must not be? The answer is, of course, negative. No generics can, and I think the code is simpler, direct, interesting (personal point of view, do not spray).

We are here to explain how to deal with this problem in Golang with some examples.

First, let's look at a bubble sort problem. The sort for an integer array slice.

package mainimport ("fmt")func bubbleSort(array []int) {for i := 0; i < len(array); i++ {for j := 0; j < len(array)-i-1; j++ {if array[j] > array[j+1] {array[j], array[j+1] = array[j+1], array[j]}}}}func main() {a1 := []int{3, 2, 6, 10, 7, 4, 6, 5}bubbleSort(a1)fmt.Println(a1)}

Online operating Address: https://www.bytelang.com/o/s/c/H8uLEIC6dA0=

The above example output is:

[2 3 4 5 6 6 7 10]

So, what if we want this bubblesort to be able to support the sort of float type data at the same time, or to sort by the length of the string? In other examples, such as the Java language, we can define bubblesort as a sort that supports generics, but not in go. To achieve this, we can use interface to achieve the same functionality.

For the sorting problem above, we can analyze the sorting steps:

    1. View the length of the slice to use to traverse the element (Len);
    2. Compare two elements in a slice (less);
    3. Determines whether to swap the element position (swap) based on the result of the comparison.
      Here, perhaps you already understand, we can break up the above function into a support any type of interface, any other type of data as long as the implementation of this interface, you can use the function in this interface to sort.
type Sortable interface{Len() intLess(int, int) boolSwap(int, int)}

Below, let's use a few examples to describe the use of this interface.

 package mainimport ("FMT") type sortable interface {Len () intless (int, int) boolswap (int , int)}func Bubblesort (array sortable) {for i: = 0; i < array. Len (); i++ {for J: = 0; J < Array. Len ()-i-1; J + + {if array. Less (j+1, j) {array. Swap (J, j+1)}}}}//The integer slice that implements the interface type Intarr []intfunc (array intarr) len () int {return Len (array)}func (array intarr) less (i in T, J Int) bool {return array[i] < Array[j]}func (array intarr) Swap (i int, j int) {Array[i], array[j] = array[j], array [I]}  The string that implements the interface, sorted by length type Stringarr []stringfunc (array Stringarr) len () int {return Len (array)}func (array Stringarr) less (i  int, J int) bool {return len (Array[i]) < Len (Array[j])}func (array Stringarr) Swap (i int, j int) {Array[i], array[j] = ARRAY[J], array[i]}//test func main () {intArray1: = intarr{3, 4, 2, 6, ten, 1}bubblesort (intArray1) fmt. Println (intArray1) StringArray1: = stringarr{"Hello", "I", "AM", "Go", "Lang"}bubblesort (stringArray1) fmt. Println (stringArray1)}  

Online Operation Address: https://www.bytelang.com/o/s/c/J_thL5dPXxI=

The output is:

[1 2 3 4 6 10][i am go lang hello]

In the example above, we first define an integer slice type of intarr type, then let the type implement the sortable interface, and then in the test code, the Intarr type can invoke the Bubblesort method of the sortable interface directly.

In addition, we have shown an example of string slice type Stringarr sorted by string length. Like the Intarr type, it implements a method that sortable can define, and then it can be sorted using sortable-capable bubblesort methods.

Summarize
The above example is a method that supports so-called "generics" in Golang. This generics, of course, is not the true meaning of generics, but provides a reference implementation for multiple types of conformance methods.

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.