룬이란 무엇입니까?
rune
in in 이란 무엇입니까 ?
인터넷 검색을 해왔지만 Golang은 한 줄로만 말합니다 :은의 rune
별칭입니다int32
.
그러나 스와핑 케이스처럼 정수가 어떻게 사용됩니까?
다음은 함수 스왑 케이스입니다. 모든 무엇 <=
과 -
?
그리고 왜 switch
논쟁이 없습니까?
&&
말은해야 하고 있지만 무엇입니까 r <= 'z'
?
func SwapRune(r rune) rune {
switch {
case 'a' <= r && r <= 'z':
return r - 'a' + 'A'
case 'A' <= r && r <= 'Z':
return r - 'A' + 'a'
default:
return r
}
}
그들 대부분은 http://play.golang.org/p/H6wjLZj6lW 에서 온
func SwapCase(str string) string {
return strings.Map(SwapRune, str)
}
나는 이것이 스왑 된 문자열을 반환 할 수 있도록 매핑하고 있음 rune
을 이해 string
합니다. 하지만 난 방법을 정확하게 이해하지 않는다 rune
또는 byte
여기에 작동합니다.
룬 리터럴은 32 비트 정수 값입니다 ( 자신의 유형을 변경할 수 있습니다, 그러나 그들이있는 거 유형이 지정되지 않은 상수 ). 유니 코드 코드 포인트를 나타냅니다. 예를 들어, 룬 리터럴 'a'
은 실제로 숫자 97
입니다.
따라서 프로그램은 다음과 거의 같습니다.
package main
import "fmt"
func SwapRune(r rune) rune {
switch {
case 97 <= r && r <= 122:
return r - 32
case 65 <= r && r <= 90:
return r + 32
default:
return r
}
}
func main() {
fmt.Println(SwapRune('a'))
}
해당 범위의 ASCII 와 동일한 유니 코드 매핑을 살펴 보려면 분명해야합니다 . 또한 32는 실제로 문자의 대문자와 소문자 코드 포인트 사이의 오프셋입니다. 그래서 추가하여 32
하는 'A'
, 당신이 얻을 'a'
반대 및 부사장.
Go lang 릴리스 정보 : http://golang.org/doc/go1#rune
룬은 유형입니다. 32 비트를 차지하며 유니 코드 CodePoint 를 나타냅니다 . 'ASCII'로 인코딩 된 영어 문자 세트는 128 개의 코드 포인트가 있습니다. 따라서 바이트 (8 비트) 안에 들어갈 수 있습니다. 이 (잘못된) 가정에서 C는 문자를 'bytes'로 char
, 'strings'를 '문자 순서'로 취급했습니다 char*
.
하지만 그거 알아. 'abcde ..'기호 외에 인간이 발명 한 다른 기호가 많이 있습니다. 그리고 그것을 인코딩하기 위해 32 비트가 필요한 것이 너무 많습니다.
golang에서 a string
는 일련의 bytes
입니다. 그러나 여러 바이트가 룬 코드 포인트를 나타낼 수 있으므로 문자열 값에도 룬이 포함될 수 있습니다. 따라서으로 변환 []rune
하거나 그 반대로 변환 할 수 있습니다 .
유니 코드 패키지 http://golang.org/pkg/unicode/ 는 풍부한 도전을 맛볼 수 있습니다.
fabrizioM의 답변에 의견을 게시 할만 큼 평판이 충분하지 않으므로 대신 여기에 게시해야합니다.
파브리 치오의 대답은 대체로 정확하고 분명히 문제의 본질을 포착했습니다.
문자열은 반드시 일련의 룬일 필요 는 없습니다 . 그것은 '바이트 슬라이스' 에 대한 래퍼 이며, 슬라이스 는 Go 배열에 대한 래퍼입니다. 이것이 어떤 차이가 있습니까?
A rune type is necessarily a 32-bit value, meaning a sequence of values of rune types would necessarily have some number of bits x*32. Strings, being a sequence of bytes, instead have a length of x*8 bits. If all strings were actually in Unicode, this difference would have no impact. Since strings are slices of bytes, however, Go can use ASCII or any other arbitrary byte encoding.
String literals, however, are required to be written into the source encoded in UTF-8.
Source of information: http://blog.golang.org/strings
I have tried to keep my language simple so that a layman understands rune
.
A rune is a character. That's it.
It is a single character. It's a character from any alphabet from any language from anywhere in the world.
To get a string we use
double-quotes ""
OR
back-ticks ``
A string is different than a rune. In runes we use
single-quotes ''
Now a rune is also an alias for int32
...Uh What?
The reason rune is an alias for int32
is because we see that with coding schemes such as below
each character maps to some number and so it's the number that we are storing. For example, a maps to 97 and when we store that number it's just the number and so that's way rune is an alias for int32. But is not just any number. It is a number with 32 'zeros and ones' or '4' bytes. (Note: UTF-8 is a 4-byte encoding scheme)
How runes relate to strings?
A string is a collection of runes. In the following code:
package main
import (
"fmt"
)
func main() {
fmt.Println([]byte("Hello"))
}
We try to convert a string to a stream of bytes. The output is:
[72 101 108 108 111]
We can see that each of the bytes that makes up that string is a rune.
(Got a feeling that above answers still didn't state the differences & relationships between string
and []rune
very clearly, so I would try to add another answer with example.)
As @Strangework
's answer said, string
and []rune
are quiet different.
Differences - string
& []rune
:
string value
is a read-only byte slice. And, a string literal is encoded in utf-8. Each char instring
actually takes 1 ~ 3 bytes, while eachrune
takes 4 bytes- For
string
, bothlen()
and index are based on bytes. - For
[]rune
, bothlen()
and index are based on rune (or int32).
Relationships - string
& []rune
:
- When you convert from
string
to[]rune
, each utf-8 char in that string becomes arune
. - Similarly, in the reverse conversion, when convert from
[]rune
tostring
, eachrune
becomes a utf-8 char in thestring
.
Tips:
- You can convert between
string
and[]rune
, but still they are different, in both type & overall size.
(I would add an example to show that more clearly.)
Code
string_rune_compare.go:
// string & rune compare,
package main
import "fmt"
// string & rune compare,
func stringAndRuneCompare() {
// string,
s := "hello你好"
fmt.Printf("%s, type: %T, len: %d\n", s, s, len(s))
fmt.Printf("s[%d]: %v, type: %T\n", 0, s[0], s[0])
li := len(s) - 1 // last index,
fmt.Printf("s[%d]: %v, type: %T\n\n", li, s[li], s[li])
// []rune
rs := []rune(s)
fmt.Printf("%v, type: %T, len: %d\n", rs, rs, len(rs))
}
func main() {
stringAndRuneCompare()
}
Execute:
go run string_rune_compare.go
Output:
hello你好, type: string, len: 11
s[0]: 104, type: uint8
s[10]: 189, type: uint8
[104 101 108 108 111 20320 22909], type: []int32, len: 7
Explanation:
The string
hello你好
has length 11, because first 5 chars each take 1 byte only, while the last 2 Chinese chars each takes 3 bytes.- Thus,
total bytes = 5 * 1 + 2 * 3 = 11
- Since
len()
on string is based on bytes, thus the first line printedlen: 11
- Since index on string is also based on bytes, thus the following 2 lines print values of type
uint8
(sincebyte
is an alias type ofuint8
, in go).
- Thus,
When convert the
string
to[]rune
, it found 7 utf8 chars, thus 7 runes.- Since
len()
on[]rune
is based on rune, thus the last line printedlen: 7
. - If you operate
[]rune
via index, it will access base on rune.
Since each rune is from a utf8 char in the original string, thus you can also say bothlen()
and index operation on[]rune
are based on utf8 chars.
- Since
Everyone else has covered the part related to runes, so I am not going to talk about that.
However, there is also a question related to switch
not having any arguments. This is simply because in Golang, switch
without an expression is an alternate way to express if/else logic. For example, writing this:
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
is same as writing this:
t := time.Now()
if t.Hour() < 12 {
fmt.Println("It's before noon")
} else {
fmt.Println("It's after noon")
}
You can read more here.
A rune is an int32 value, and therefore it is a Go type that is used for representing a Unicode code point. A Unicode code point or code position is a numerical value that is usually used for representing single Unicode characters;
참고URL : https://stackoverflow.com/questions/19310700/what-is-a-rune
'IT' 카테고리의 다른 글
파이썬에서 '@ ='기호는 무엇입니까? (0) | 2020.06.05 |
---|---|
pytest에서 conftest.py 파일의 용도는 무엇입니까? (0) | 2020.06.05 |
왜 "HTTP는 상태 비 저장 프로토콜"이라고되어 있습니까? (0) | 2020.06.05 |
Vcode에서 Xcode5의 * .xccheckout 파일을 무시해야합니까? (0) | 2020.06.05 |
비트 마스킹이란 무엇입니까? (0) | 2020.06.05 |