10

golang类型转换与断言

 3 years ago
source link: https://studygolang.com/articles/35289
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

golang类型转换与断言

13641329565 · 1天之前 · 100 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

使用方式:

int64(a) // 类型转换

v, ok := a.(typeName) //类型断言

  总结: 相似:都是右边有括号。 区别:断言有.     类型转换demo:

package main
import (
  "github.com/davecgh/go-spew/spew"
)

func main() {
  var age int

  age = 18

  // int转int64
  ageInt64 := int64(age) 

  spew.Dump(ageInt64)
}
// 输出
(int64) 18

  断言demo:

package main

import (

"github.com/davecgh/go-spew/spew"
)

type XiaoYi struct {
  age int
}

func main() {
  var xy interface{}

  xy = XiaoYi{
    age: 18,
  }

  originType, ok := xy.(XiaoYi)

  spew.Dump(originType)
  spew.Dump(ok)
}
// 输出
(main.XiaoYi) {
 age: (int) 18
}

(bool) true

Recommend

  • 31
    • studygolang.com 6 years ago
    • Cache

    golang: 类型转换和类型断言

    类型转换在程序设计中都是不可避免的问题。当然有一些语言将这个过程给模糊了,大多数时候开发者并不需要去关注这方面的问题。但是golang中的类型匹配是很严格的,不同的类型之间通常需要手动转换,编译器不会代你去做这个事。我之所以说...

  • 53

    通过类型断言(type assertion)方式来判断接口的具体类型, Sometimes, you may want to know the exact type of an interface variable. In this scenario, you can use type assertion : x.(T)

  • 26
    • studygolang.com 5 years ago
    • Cache

    类型转换和断言

    Golang不支持隐式类型转换 普通类型转换 普通类型转换可以转换不同但是相互兼容的类型,例如int与float,int与rune,但是string与数字类型是不能进行普通类型转换的。 例如: a = 123 x := i...

  • 44
    • Github github.com 5 years ago
    • Cache

    谈谈 TypeScript 中的类型断言

    类型断言 类型断言(Type Assertion)可以用来手动指定一个值的类型。 语法 值 as 类型 或 <类型>值 在 tsx 语法(React 的 jsx 语法的 ts 版)中必须使用前者,即

  • 18

    Hi,大家好,我是明哥。 在自己学习 Golang 的这段时间里,我写了详细的学习笔记放在我的个人微信公众号 《Go编程时光》,对于 Go 语言,我也算是个初学者,因此写的东西应该会比较适合刚接触的同学,如果你也是刚学习 Go 语言,不...

  • 38
    • studygolang.com 4 years ago
    • Cache

    Go之断言类型(assert type)

    1.背景介绍: 笔者最近在使用一个数据结构实现多个接口,但是却发现想要在一段时间内转换成接口1,另外一段时间转换成接口2,所以也就使用到了断言类型。在看过断言类型之后,觉得还是很有必要讲一讲这个断言类型,于是...

  • 19
    • studygolang.com 4 years ago
    • Cache

    聊聊golang的类型断言

    序 本文主要研究一下golang的类型断言 类型断言 x.(T) 断言x不为nil且x为T类型 如果T不是接口类型,则该断言x为T类型 如果T类接口类型,则该断言x实现了T接口

  • 9
    • www.sulinehk.com 3 years ago
    • Cache

    Golang 类型断言的分类和例子

    因为对表达式断言和赋值断言的理解不够清晰,所以写了这篇博客来加深理解。为了更好地理解类型断言的例...

  • 7
    • studygolang.com 2 years ago
    • Cache

    Golang中的类型和类型断言

    Golang中的类型和类型断言 LeeYubo · 2019-04-26 17:14:08 · 8268 次点击...

  • 6
    • zhangyiming748.github.io 1 year ago
    • Cache

    golang interface 的类型断言

    golang interface 的类型断言 2023-11-07 Golang ...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK