0
package main

import (
    "fmt"
    _ "math"
    "unsafe"
)

func main() {
    var s1 = "한글"
    fmt.Println(s1[0]);
}

I want to extract string element like s1[0]. But I didn't get the correct element. Just returned number. I don't know the meaning of the number. I think there'is a library which is unicode/utf8. But I don't know how I get the correct value from the element using this. I want to extract '한' this word. Can you help me how I can convert?

Reza Mousavi
  • 4,420
  • 5
  • 31
  • 48
namyulbae
  • 87
  • 6

1 Answers1

1
package main

import (
    "fmt"
)

func main() {
    var s1 = "한글"
    var s2 = []rune(s1)
    fmt.Println(string(s2[0]))
}
ru10
  • 826
  • 9
  • 10
  • Thanks for your help. I've resolved this problem. – namyulbae Oct 18 '18 at 06:31
  • This answer lacks what I consider crucial—in the Go land: an assessment of performance implications. For a two-character string, producing a slice of runes from it in order to get the first one and then immediately throwing it away is, a so-called "code smell" (I'd fathom the author came from web frontend scripting), but if the string would have been read from the outside and is of unknown length, the memory waste for such a simple operation would not be negligible, and could even be possibly exploited externally by a malicious entity. – kostix Oct 18 '18 at 13:01
  • Go is explicitly a no-frills, no-nonsense, no-magic language, and it expects the developers using it actually think about the characteristics of the code they write. To that end, the language tries hard not to hard the complexity (in time and space) from the programmer. Type-conversion of `strings` to `[]rune` and `[]byte` (and vice-versa) is one place where the cost is hidden—because otherwise the language would need to drop a feature too convenient to omit. And that's why it requires extra care. – kostix Oct 18 '18 at 13:03