Golang泛型中关键词【any】表示任意类型;
基本款
1. Java版
public class Point<T> {
private T x;
public void setX(T x) {
this.x = x;
}
public T getX() {
return this.x;
}
public static void main(String[] args) {
Point<Integer> pointInt = new Point<>();
pointInt.setX(100);
System.out.println("Integer x=" + pointInt.getX());
Point<String> pointStr = new Point<>();
pointStr.setX("字符串");
System.out.println("String x=" + pointStr.getX());
}
}
标准输出:
Integer x=100
String x=字符串
1. Golang版
package main
import "fmt"
type Point[T any] struct {
x T
}
func (n Point[T]) GetX() T {
return n.x
}
func main() {
pointInt := Point[int]{}
pointInt.x = 100
fmt.Printf("int x=%d\n", pointInt.GetX())
pointStr := Point[string]{}
pointStr.x = "字符串"
fmt.Printf("string x=%s\n", pointStr.GetX())
}
标准输出:
int x=100
string x=字符串
1.1 Java版多参数泛型
public class Point<T, O> {
private T x;
private O y;
public void setX(T x) {
this.x = x;
}
public T getX() {
return this.x;
}
public void setY(O y) {
this.y = y;
}
public O getY() {
return this.y;
}
public static void main(String[] args) {
Point<Integer, String> point = new Point<>();
point.setX(100);
point.setY("字符串");
System.out.println("Integer x=" + point.getX() + ", String y=" + point.getY());
}
}
标准输出:
Integer x=100, String y=字符串
1.1 Golang版多参数泛型
import (
"fmt"
)
type Point[T any, O any] struct {
x T
y O
}
func (n Point[T, O]) GetX() T {
return n.x
}
func (n Point[T, O]) GetY() O {
return n.y
}
func main() {
point := Point[int, string]{}
point.x = 100
point.y = "字符串"
fmt.Printf("int x=%d, string y=%s\n", point.GetX(), point.GetY())
}
标准输出:
int x=100, string y=字符串
类型约束 <? extends T> 上界通配符(Upper Bounds Wildcards)
2. Java版
public class Point<T extends Number> {
private T x;
public void setX(T x) {
this.x = x;
}
public T getX() {
return this.x;
}
public static void main(String[] args) {
Point<Integer> pointInt = new Point<>();
pointInt.setX(100);
System.out.println("Integer x=" + pointInt.getX());
Point<Float> pointStr = new Point<>();
pointStr.setX(1.8f);
System.out.println("Float x=" + pointStr.getX());
if (pointInt.getClass() == pointFloat.getClass()) {
// 结果为相同类型
System.out.println("相同类型");
}
}
}
标准输出:
Integer x=100
Float x=1.8
相同类型
2. Golang版
import (
"fmt"
"reflect"
)
type Number interface {
int | int32 | float32 | float64
}
type Point[T Number] struct {
x T
}
func (n Point[T]) GetX() T {
return n.x
}
func main() {
pointInt := Point[int]{}
pointInt.x = 100
fmt.Printf("int x=%d\n", pointInt.GetX())
pointFloat := Point[float32]{}
pointFloat.x = 1.8
fmt.Printf("float32 x=%f\n", pointFloat.GetX())
if reflect.TypeOf(pointInt) == reflect.TypeOf(pointFloat) {
fmt.Println("相同类型")
} else {
// 结果为 不同类型
fmt.Println("不同类型")
}
}
标准输出:
int x=100
float32 x=1.800000
不同类型