I've expected tag to be "account" but it is "ccount". Why is "a" removed?
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimLeft(s, "refs/tags")
fmt.Println(tag)
}
Run
Use TrimPrefix instead of TrimLeft
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimPrefix(s, "refs/tags/")
fmt.Println(tag)
}
Please notice that following TrimLeft calls will result the same "fghijk
" string:
package main
import (
"fmt"
"strings"
)
func main() {
s := "/abcde/fghijk"
tag := strings.TrimLeft(s, "/abcde")
fmt.Println(tag)
tag = strings.TrimLeft(s, "/edcba")
fmt.Println(tag)
}
So TrimLeft is not the method which fits your needs. I guess it's impossible to use it in the example you've given to get the result you expect.
It is working as documented:
TrimLeft returns a slice of the string s with all leading Unicode
code points contained in cutset removed
Because there's an 'a' in the first argument (the cutset) the leading 'a' in account is removed
Related
I have the following in the intepreter of Tour of Go:
package main
import (
"golang.org/x/tour/wc"
str "strings"
)
func WordCount(s string) map[string]int {
results := make(map[str]int)
words := str.Fields(s)
return map[string]int{"x": 1}
}
//func main() {
// wc.Test(WordCount)
//}
This is based on https://tour.golang.org/moretypes/23
My error is
tmp/sandbox169629521/main.go:9: use of package str without selector
Trying
results := make(map[str.string]int)
now fails with
tmp/sandbox424441423/main.go:9: cannot refer to unexported name strings.string
tmp/sandbox424441423/main.go:9: undefined: strings.string
"string" is a builtin. You don't need to do strings.string:
Docs: https://golang.org/pkg/builtin/#string
I'm going through the Golang tutorial, and I am on this part
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("My favorite number is", rand.Seed)
}
This returns My favorite number is 0xb1c20
I have been reading on https://golang.org/pkg/math/rand/#Seed but I'm still a bit confused as to how have it instead of show the hex show a string
math/rand.Seed is a function; you are printing the function's location in memory. You probably meant to do something like the following:
package main
import (
"fmt"
"math/rand"
)
func main() {
rand.Seed(234) // replace with your seed value, or set the seed based off
// of the current time
fmt.Println("My favorite number is", rand.Int())
}
I am new to go programming language and I'm stock on this scenario on my code.
Here's my example code:
a := genreAPI{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println("Value of a :", a)
The current output is: Value of a : [{Pop} {Rock}]
How can I achieved an output like this:
Value of a : [{UG9w} {Um9jaw==}]
which is a base64 encode?
I am not sure what exactly is not clear from the documentation. Not only it has a clear name which explains states what the method is doing, it also has an example.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("Pop")
str := base64.StdEncoding.EncodeToString(data)
fmt.Println(str) // UG9w
}
Go Playground
You can customise the output of print functions by providing a String() method for your type. Either for the whole Genre or just for the name variable.
Example:
package main
import (
"encoding/base64"
"fmt"
)
type Base64String string
func (b Base64String) String() string {
return base64.StdEncoding.EncodeToString([]byte(b))
}
type Genre struct {
Name Base64String
}
func main() {
a := []Genre{Genre{"Pop"}, Genre{"Rock"}}
fmt.Println(a) // prints [{UG9w} {Um9jaw==}]
fmt.Println(string(a[0].Name)) // prints Pop
}
I want to pass a compiled regex to golang function, e.g.
package main
import "fmt"
import "regexp"
func foo(r *Regexp) {
fmt.Println(r)
}
func main() {
r, _ := regexp.Compile("p([a-z]+)ch")
foo(r)
}
But it is showing "undefined: Regexp"
Any hints?
Use a qualified identifier. For example,
package main
import "fmt"
import "regexp"
func foo(r *regexp.Regexp) {
fmt.Println(r)
}
func main() {
r, _ := regexp.Compile("p([a-z]+)ch")
foo(r)
}
Output:
p([a-z]+)ch
Qualified identifiers
A qualified identifier is an identifier qualified with a package name
prefix. Both the package name and the identifier must not be blank.
QualifiedIdent = PackageName "." identifier .
A qualified identifier accesses an identifier in a different package,
which must be imported. The identifier must be exported and declared
in the package block of that package.
math.Sin // denotes the Sin function in package math
You can also use a dot import:
package main
import (
"fmt"
. "regexp"
)
func foo(r *Regexp) {
fmt.Println(r)
}
func main() {
r := MustCompile("p([a-z]+)ch")
foo(r)
}
However, typically it will be better to use use the fully qualified name.
https://golang.org/ref/spec#Import_declarations
I'm using the flag module to parse my flags, but want to have at least one positional argument. How do I show the usage help when not enough positional arguments are present, as I would in python with parser.error?
Currently, I am manually calling os.Exit, but that feels really cumbersome for what should be a simple error:
package main
import "flag"
import "fmt"
import "os"
func main() {
flag.Parse()
if flag.NArg() != 1 {
println("This program needs exactly one argument")
flag.Usage()
os.Exit(2)
}
fmt.Printf("You entered %d characters", len(flag.Args()[0]))
}
To do things like this, I use the log package.
package main
import "flag"
import "fmt"
import "os"
import "log"
func main() {
flag.Parse()
if flag.NArg() != 1 {
log.Fatalln("This program needs exactly one argument")
}
fmt.Printf("You entered %d characters", len(flag.Args()))
}
log.Fatal() and it's sister methods (log.Fatalln(), log.Fatalf() etc) are all helpers that simply do log.Print() and then follow it up with os.exit(1).
Edit -- Adding link
http://golang.org/pkg/log/#Fatalln