Bez startu i końca funkcji w Go?

Z ciekawości: dlaczego nie ma standardowych funkcji, takich jak startswith, endswith, itp jako części standardowych bibliotek w języku programowania Go?

 157
Author: Sahas, 2012-11-06

2 answers

Pakiet strings zawiera HasPrefix i HasSuffix .

import "strings"

startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true

Play.golang.org

 275
Author: Kyle Finley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-06 04:05:29

Jeśli pracujesz z bajtami, możesz używać tych funkcji z bajtów "opakowanie": {]}

package main

import (
   "bytes"
   "fmt"
)

func main() {
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}

Będzie to mniej kosztowne niż konwersja na string. Przydatne, jeśli czytasz z żądania HTTP lub odczytu z pliku lokalnego.

 1
Author: Steven Penny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-17 21:21:14