接口包含类型约束:不能在转换中使用接口
来源:stackoverflow
时间:2024-04-18 10:57:36 452浏览 收藏
从现在开始,努力学习吧!本文《接口包含类型约束:不能在转换中使用接口》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
问题内容
type Number interface { int | int64 | float64 } type NNumber interface { } //interface contains type constraints //type NumberSlice []Number type NNumberSlice []NNumber func main() { var b interface{} b = interface{}(1) fmt.Println(b) // interface contains type constraints // cannot use interface Number in conversion (contains specific type constraints or is comparable) //a := []Number{Number(1), Number(2), Number(3), Number(4)} //fmt.Println(a) aa := []interface{}{interface{}(1), interface{}(2), interface{}(3), 4} fmt.Println(aa) aaa := []NNumber{NNumber(1), NNumber(2), NNumber(3), 4} fmt.Println(aaa) }
为什么 number
切片 a
无法这样初始化?
numberslice
和 nnumberslice
看起来很相似,但是什么意思类型约束,看起来语法很奇怪
正确答案
语言规范明确禁止使用带有类型元素的接口作为类型参数约束之外的任何内容(引用位于第 Interface types 段下):
非 basic 的接口只能用作类型约束,或用作用作约束的其他接口的元素。它们不能是值或变量的类型,也不能是其他非接口类型的组件。
嵌入 comparable
或其他非基本接口的接口也是非基本接口。您的 number
接口包含一个联合,因此它也是非基本的。
一些例子:
// basic: only methods type a1 interface { getname() string } // basic: only methods and/or embeds basic interface type b1 interface { a1 setvalue(v int) } // non-basic: embeds comparable type message interface { comparable content() string } // non-basic: has a type element (union) type number interface { int | int64 | float64 } // non-basic: embeds a non-basic interface type specialnumber interface { number isspecial() bool }
在变量 a
的初始化中,您尝试在类型转换 number(1)
中使用 number
,这是不允许的。
您只能使用 number
作为类型参数约束,即限制泛型类型或函数实例化所允许的类型。例如:
type Coordinates[T Number] struct { x, y T } func sum[T Number](a, b T) T { return a + b }
好了,本文到此结束,带大家了解了《接口包含类型约束:不能在转换中使用接口》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习