Golang 挖坑之旅——类型理解

本文探讨了Golang中的类型声明,包括别名声明与类型定义,强调了它们的区别。同时,解释了基本类型的底层类型概念,以及如何判断两个类型是否相同。此外,文章还讨论了命名类型与未命名类型(在Go 1.9之前的区别),并举例说明了类型互换的规则。最后,总结了理解这些概念的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Golang 挖坑之旅——类型理解

0. 问题描述

参考官网文档来理解type时,遇上了一些模糊的概念问题,在此开一篇文章作为记录使用,涉及概念named typeunnamed typealias declarationtype definitionunderlying typedefined type

注:通篇整英文单词是因为很多中文的翻译各个地方都有所差异。

1. Type Declaration

A type declaration binds an identifier, the type name, to a type. Type declarations come in two forms: alias declarations and type definitions.

官网对于类型的声明有两种,一种是alias declaration,另一种是type definition,这两种有非常大的区别,先用一个简短的例子展示:

// alias declaration
type (
	nodeList = []*Node  // nodeList and []*Node are identical types
	Polar    = polar    // Polar and polar denote identical types
)

// type definition
type (
	Point struct{
    x, y float64 }  // Point and struct{ x, y float64 } are different types
	polar Point                   // polar and Point denote different types
)

二者在产生的类型和source type的关系上,上有本质区别,alias不产生新的type,而通过type definition得到的defined type,不论source type是啥,全都是不一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值