I'm converting a byte slice to a string and trying to catch this in a switch case. (Not sure how to catch byte slices, therefore conversion).
I can't figure out how to get my switch statement to work.
What am I missing?
package main
import "os/exec"
func main() {
// Query existing layout
cmd, _ := exec.Command("setxkbmap", "-query").Output()
// Retrieve the language, cant figure out a better way
lang := string(cmd[len(cmd)-3:])
// Switch to the other language
var newLang string
print(lang) // prints gb
switch lang {
case "se": newLang = "gb"
case "gb": newLang = "se"
}
print(newLang) // prints nothing
// set new layout
exec.Command("setxkbmap", "-layout", newLang)
}
Given the output of setxkbmap -query
can have multiple rows, and the value you are looking for (which I assume is layout
) isn't necessarily always the last one printed, I suggest reading each line of the output, checking for the layout:
field and then assigning the value.
For example:
out, err := exec.Command("setxkbmap", "-query").Output()
if err != nil {
return err
}
var layout string
s := bufio.NewScanner(bytes.NewReader(out))
for s.Scan() {
fields := strings.Fields(s.Text())
if len(fields) != 2 {
continue
}
if fields[0] == "layout:" {
layout = fields[1]
break
}
}
switch layout {
case "gb":
// handle gb layout
fmt.Println("got gb layout")
return nil
default:
return fmt.Errorf("unexpected layout: %q", layout)
}