Home >Backend Development >Golang >Does golang not support generics?

Does golang not support generics?

(*-*)浩
(*-*)浩Original
2019-12-13 14:26:553486browse

Does golang not support generics?

#The Golang team believes that the complexity of the type system and runtime is too costly, and has not yet found a good design that can offset this complexity.

The built-in map and slice actually have a generic flavor. In addition, interface{} can be used to construct a container, which can achieve a generic effect. So there is no direct support for generics so far. (Recommended learning: Go )

We intend to explain how to deal with this problem in Golang.

First, let’s look at a bubble sorting problem. Sorting of slices of integer arrays.

package main

import (
	"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)
}

The output of the above example is:

[2 3 4 5 6 6 7 10]

So, if we hope that this bubbleSort can also support float type data sorting, or sort according to the length of the string What should I do?

In other languages ​​such as java, we can define bubbleSort to support generic sorting, but this is not possible in Go. To achieve this purpose, we can use interface to achieve the same functionality.

In response to the above sorting problem, we can analyze the steps of sorting:

Check the slice length to traverse the elements (Len);

Compare two elements in the slice (Less);

Decide whether to swap element positions (Swap) based on the comparison result.

At this point, maybe you already understand that we can decompose the above function into an interface that supports any type. Any other type of data can be processed using the functions in this interface as long as it implements this interface. Sorted.

The above is the detailed content of Does golang not support generics?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn