As a fast, statically typed programming language with a garbage collection mechanism, Go language has the advantages of high readability, simple syntax, and does not sacrifice the performance of the code. During development, some common Golang methods are often forgotten, and these methods are the key to helping us improve development efficiency. This article will introduce some common methods in Golang.
String operations are very common in programming, and Golang also provides many built-in methods to process strings. The following are some commonly used string operations:
len(str)
: Get the string lengthstrings.Contains(str, substr)
: Determine whether the string str
contains a substring substr
strings.HasPrefix(str, prefix)
: Determine whether the string str
Whether to be prefixed by prefix
strings.HasSuffix(str, suffix)
: Determine whether the string str
With suffix
as the suffixstrings.Index(str, substr)
: Get the first occurrence of substring# in the string str
The position of ##substr, if not, return
-1
: Get the string
str# The position of the last occurrence of substring substr
in ##, if not, return -1
##strings.Replace(str, old, new, n)
old in the string
str with
new
strings.Split(str, sep) into slices by
sep
strings.ToLower(str)
strings.ToUpper(str)
2. Array and slice operations##len(arr)
: Get the array lengthlen(slice)
: Get the slice lengthcap(slice)
: Get the slice capacityarr[index]
: Get the element at the specified index in the arrayslice[index]
: Get the element with the specified index in the sliceslice[start:end]
: Intercept the sliceappend(slice, elem)
: Append elements to the slice copy(dest, src)
: Copy the elements in the source slice dest
3. Map operation
len(map)
: Get the map lengthmap[key]
: Get the map The value of the specified key in delete(map, key)
: Delete the key-value pair of the specified key from the mapfor key, value := range map
: Traverse all key-value pairs in the map4. File operations
os.Create(name)
: Create a new fileos.Open(name)
: Open the fileos.OpenFile(name, flag, perm)
: Open the file with the specified flag and modedefer file.Close()
: Close the file at the end of the function bufio.NewReader(file)
: Create a file cache reader io.Copy(dest, src )
: Copy the content of the source file to the target fileioutil.ReadFile(filename)
: Read the file content as a byte array5. Time and date operations
: Get the current time
: Convert time into a string according to the specified format string
: Parse the given string according to the specified format For time
: Get the number of seconds of the duration
: Get the duration Minutes of time
The above is the detailed content of Golang common methods. For more information, please follow other related articles on the PHP Chinese website!