golang rune() 函数是如何工作的 [英] golang how does the rune() function work

查看:41
本文介绍了golang rune() 函数是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上发现了一个使用 golang 中的 rune() 函数的函数,但我很难找到它是什么.我正在阅读教程并且对文档缺乏经验,因此很难找到我正在寻找的内容.

I came across a function posted online that used the rune() function in golang, but I am having a hard time looking up what it is. I am going through the tutorial and inexperienced with the docs so it is hard to find what I am looking for.

具体来说,我想知道为什么会失败......

Specifically, I am trying to see why this fails...

fmt.Println(rune("foo"))

这不会

fmt.Println([]rune("foo"))

推荐答案

rune 是 Go 中的一种类型.它只是 int32 的别名,但通常用于表示 Unicode 点.rune() 不是函数,而是将类型转换为 rune 的语法.Go 中的转换总是使用 type() 语法,这可能会使它们看起来像函数.

rune is a type in Go. It's just an alias for int32, but it's usually used to represent Unicode points. rune() isn't a function, it's syntax for type conversion into rune. Conversions in Go always have the syntax type() which might make them look like functions.

第一部分代码失败,因为 Go 中没有定义字符串到数字类型的转换.然而,字符串到 runes/int32s 切片的转换在语言规范中是这样定义的:

The first bit of code fails because conversion of strings to numeric types isn't defined in Go. However conversion of strings to slices of runes/int32s is defined like this in language specification:

将字符串类型的值转换为符文类型的切片会产生一个包含字符串的各个 Unicode 代码点的切片.[golang.org]

Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. [golang.org]

因此,您的示例打印了一片值为 102、111 和 111 的符文

So your example prints a slice of runes with values 102, 111 and 111

这篇关于golang rune() 函数是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆