Go语言学习笔记-A Tour of Go 练习笔记-Generic types

Generic types

练习题目:

In addition to generic functions, Go also supports generic types. A type can be parameterized with a type parameter, which could be useful for implementing generic data structures.

This example demonstrates a simple type declaration for a singly-linked list holding any type of value.

As an exercise, add some functionality to this list implementation.

练习程序:

package main
import "fmt"

// List represents a singly-linked list that holds
// values of any type.
type List[T any] struct {
	next *List[T]
	val  T
}

func AddList[T any](x T) List[T] {
    i := List[T]{}
	i.next = &i
	i.val = x
	return i
}

func main() {
    a := List[int]{}
	a.val = 1
	list := AddList(123)
	a.next = &list
	fmt.Println("New list is", list.next, list.val)
	b := List[string]{}
	b.val = "123"
	blist := AddList("456")
	b.next = &blist
	fmt.Println("New list is", blist.next, blist.val)
}

运行结果:

New list is &{0xc000108050 123} 123
New list is &{0xc000114000 456} 456

学习笔记:该联系目的在于掌握GO语言中的泛型类型,通过定了一个可设置任意类型的Struct结构体List,实现了一个单向链表,并通过AddList函数向链表中加入链表节点。在main函数运行中,可以定义int类型的链表,也可以定义string类型的链表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值