The reason you see: %!(EXTRA uint8=10)
is you are calling Printf
without a format option. You should just call fmt.Println
instead.
10
is the encoding of the newline character.
Now, the meat of your question:
You have a byte array (slice).
You are trying to interpret it as lines (strings separated by ‘\n’).
Interpreting a byte array as a string is easy (assuming the bytes do in fact represent a utf-8 string):
// assume buf is []byte
var text = string(buf)
You want to treat this as a list of strings. Since git tag
returns lines, you can split by ‘\n’ or you can just call strings.Fields
which splits by generic whitespace (including newlines); documented here: https://golang.org/pkg/strings/#Fields
var parts = strings.Fields(text)
Now you can easily just get the last element:
parts[len(parts)-1]
But for safety you should check the list has some elements, otherwise you will crash on out-of-bounds access.
cmd := exec.Command("git", "tag")
bufOut, err := cmd.Output()
if err != nil {
log.Fatalf("cmd.Run() failed with %s\n", err)
}
textOut := string(bufOut)
parts := strings.Fields(textOut)
if len(parts) == 0 {
log.Fatal("No tags")
}
releaseVersion := parts[len(parts)-1]
fmt.Println("release version:", releaseVersion)
WHY DOES THIS GOT TO BE SO COMPLEX? IN JAVASCRIPT I CAN JUST DO pop()
It’s not really that complex. This is just how computers work. When a program runs, it has a standard output which is essentially a byte stream.
I’m guessing javascript does this step for you automatically:
textOut := string(bufOut)
parts := strings.Fields(textOut)
i.e. converting the program output to a list of strings separated by new lines.
2
solved How to return the last element in a byte array of integers