I want to write a program that accepts a character from console and display its next character.
This is what I tried:
package main
import (
"fmt"
)
func main() {
var ch int32
fmt.Printf("Enter Char : ")
fmt.Scan(&ch)
ch++
fmt.Printf("Next Char is %s ", string(ch))
}
"Characters" in Go are called runes, and rune
is an alias for int32
. You need two changes:
Scan
actually fails - check for errors!)Here's an extended example:
package main
import (
"fmt"
"log"
)
func main() {
var ch rune
fmt.Printf("Enter Char : ")
_, err := fmt.Scanf("%c", &ch)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ch = %x
", ch)
ch++
fmt.Printf("ch+1 = %x
", ch)
fmt.Printf("Next char is %c
", ch)
}
Sample session:
Enter Char : a
ch = 61
ch+1 = 62
Next char is b
Make sure to read this official Go blog post to better understand how runes and strings interact.