SoFunction
Updated on 2025-03-04

Implementation of conversion between custom types in Golang (type conversion)

The conversion between numerical values ​​and strings, or between integers and floating point types, is not discussed here. What we want to discuss here is the conversion between custom types. This conversion is different from other languages ​​and is also widely used in the source code of go.

Here are two practical examples.

Convert to a custom type that implements some interfaces (some)

For example: IntSlice in the sort package is a custom type of []int and implements the interface as shown below:

type IntSlice []int

// Methods to implement interfacesfunc (p IntSlice) Len() int      { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int)   { p[i], p[j] = p[j], p[i] }
// A convenient wayfunc (p IntSlice) Sort() { Sort(p) }

When we need to sort an int slice, we can directly convert []int] into and then directly call the Sort() method.

 ints := []int{1, 7, 2, 3, 8, 0}
 (ints).Sort()

Convert a function into a function that implements some interfaces

A typical case is that through this type, an ordinary function can be made into an Http processor.

type HandlerFunc func(ResponseWriter, *Request)

// Methods to implement interfacesfunc (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
  f(w, r)
}

As long as a function f has the same function signature as HandlerFunc, the function can be converted to. and

Implemented the interface again,Then this functionfYou can behttpThe server has been called。

func f(w ResponseWriter, r *Request) {
 //...
}

("/args", (f))

This usage is common in Golang, and can use less code to implement the same functionality as other languages.

This is the end of this article about the implementation of type conversion between custom types in Golang. For more related Golang custom type conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!