douchilian1009
douchilian1009
2016-10-16 19:45

在Golang的Scanln中使用符文而不是字符串

已采纳

Below is the code for reading the input from console

var message string
fmt.Scanln(&message)

But I wanted to try same with rune, which is unicode of byte

var input []rune
fmt.Scanln(input)

As per my C/C++ knowledge, where an array's reference can be passed through its name , I thought it would work in case of rune

But surprisingly the program passes Scanln in case of rune without even taking console input

What is that am doing wrong? Or it cannot be done ? Or it requires type casting to string ?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dpzzkfb1244 dpzzkfb1244 5年前

    What you have is a slice not an array, they're different in Go

    When you read each character from a string you will get a rune, for example:

    for _, rune := range input { ... }
    // or
    input[0] // it returns a rune
    

    Now if you want to use index or more unicode manipulation you should keep in mind that each rune has a length and that lenght affects the length of the string too, see this example to better understanding, for example you see 3 characters in the string, but the lenght is 5:

    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func main() {
    
        input := "a界c"
    
        fmt.Println(len(input))
    
        for index, rune := range input {
            fmt.Println(index, utf8.RuneLen(rune), string(rune))    
        }
    
        fmt.Println(input[1:4]) // we know that the unicode character '界'
                                // starts in index 1 and ends in index 3
    }
    

    run it here: https://play.golang.org/p/xvmH1laevS

    点赞 评论 复制链接分享

相关推荐