怎样判断一个变量的类型?

package main

import "fmt"

var container = []string{"zero", "one", "two"}

func main() {
	container := map[int]string{0: "zero", 1: "one", 2: "two"}
	fmt.Printf("The element is %q.\n", container[1])
}

怎样在打印变量container的元素之前,判断它的类型呢?

答案是:使用类型断言表达式。语法是 x.(T)

x就是要判断类型的变量,x在当下必须是接口类型的。T就是断言的变量类型。 在Go语言中,interface{}代表空接口。任何类型都是空接口的实现类型。

value, ok := interface{}(container).([]string)

上面这行代码,:=右边,是x.(T):类型断言表达式的应用。应为container不是接口类型,需要转换一下类型。

断言表达式的结果赋值给 value和ok两个变量。

转载于:https://my.oschina.net/u/3672057/blog/2967648

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 中,可以使用 `typeof` 运算符来判断变量的数据类型。`typeof` 运算符返回一个表示数据类型的字符串。 以下是一些常见的数据类型及其对应的 `typeof` 返回值: - `undefined`:表示未定义的值。使用 `typeof` 判断时,返回 `'undefined'`。 - `boolean`:表示布尔值。使用 `typeof` 判断时,返回 `'boolean'`。 - `number`:表示数字。使用 `typeof` 判断时,返回 `'number'`。 - `string`:表示字符串。使用 `typeof` 判断时,返回 `'string'`。 - `symbol`:表示符号(ES6 新增)。使用 `typeof` 判断时,返回 `'symbol'`。 - `bigint`:表示大整数(ES2020 新增)。使用 `typeof` 判断时,返回 `'bigint'`。 - `object`:表示对象(包括数组、函数、日期等)。使用 `typeof` 判断时,返回 `'object'`。请注意,`typeof null` 返回 `'object'`,这是一个历史遗留问题。 - `function`:表示函数。使用 `typeof` 判断时,返回 `'function'`。 以下是使用 `typeof` 运算符判断变量数据类型的示例: ```javascript const undefinedVariable = undefined; console.log(typeof undefinedVariable); // 'undefined' const booleanVariable = true; console.log(typeof booleanVariable); // 'boolean' const numberVariable = 42; console.log(typeof numberVariable); // 'number' const stringVariable = 'Hello'; console.log(typeof stringVariable); // 'string' const symbolVariable = Symbol('foo'); console.log(typeof symbolVariable); // 'symbol' const bigintVariable = BigInt(9007199254740991); console.log(typeof bigintVariable); // 'bigint' const objectVariable = { name: 'John' }; console.log(typeof objectVariable); // 'object' const arrayVariable = [1, 2, 3]; console.log(typeof arrayVariable); // 'object' const functionVariable = function() {}; console.log(typeof functionVariable); // 'function' ``` 需要注意的是,`typeof` 运算符对于对象(包括数组和函数)返回的都是 `'object'`。如果需要更准确地判断对象的具体类型,可以使用其他方法,比如 `Array.isArray()` 判断是否为数组,`instanceof` 运算符判断是否为特定类型的实例等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值