2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.