golang 泛型

本次测试 go1.18版本

泛型函数

package main

import "fmt"

func testSlice[T any](s []T) {
	for _, v := range s {
		fmt.Println(v)
	}
}

func main() {
	testSlice[int64]([]int64{123, 456, 789})
	testSlice[float64]([]float64{123.3, 456.6, 789.9})
	testSlice[string]([]string{"你好", "世界", "2022"})
}

泛型切片 

package main

import "fmt"

type n[T any] []T

func testSlice[T any](s []T) {
	for _, v := range s {
		fmt.Println(v)
	}
}

func main() {
	n1 := n[int64]{22, 55}
	testSlice(n1)
	s1 := n[string]{"你好", "世界"}
	testSlice(s1)
}

泛型map

package main

import "fmt"

type m[K string, V any] map[K]V

func main() {
	m1 := m[string, int]{"key1": 1}

	m2 := m[string, string]{"key2": "value2"}

	fmt.Println(m1, m2)
}

泛型channel  

package main

import "fmt"

type ch[C any] chan C

func main() {
	c1 := make(ch[int], 4)
	c1 <- 3

	c2 := make(ch[string], 2)
	c2 <- "Hello World"

	fmt.Println(<-c1)
	fmt.Println(<-c2)
}

  

  

 

posted @ 2022-03-31 10:10  昌慶  阅读(189)  评论(0编辑  收藏  举报