当前位置:网站首页>Hello go (XII). Go language common standard library II

Hello go (XII). Go language common standard library II

2022-06-11 17:55:00 Tianshan old demon

One 、os

1、os brief introduction

os The package provides a platform independent interface to the operating system functions , Design image Unix style , But error handling is go style , When os When the bag is in use , If the error type is returned instead of the number of errors .

2、os Common interfaces

func Hostname() (name string, err error) // Hostname Return the hostname provided by the kernel 
func Environ() []string // Environ The format of the returned environment variable is ”key=value” A sliced copy of the string 
func Getenv(key string) string //  Getenv Retrieve and return a file named key The value of the environment variable 
func Getpid() int // Getpid Returns the process of the caller's process ID
func Exit(code int) // Exit Let the current program with the given status code code sign out . Generally speaking , Status code 0 It means success , Not 0 It means that something has gone wrong . The program will terminate immediately ,defer The function will not be executed 
func Stat(name string) (fi FileInfo, err error) //  Get file information 
func Getwd() (dir string, err error) // Getwd Return a root path corresponding to the current working directory 
func Mkdir(name string, perm FileMode) error //  Create a directory with the specified permissions and name 
func MkdirAll(path string, perm FileMode) error //  Create a directory with the specified permissions and name , Include any necessary parent directories , And back to nil, Otherwise, an error is returned 
func Remove(name string) error //  Delete name Specified file or directory 
func TempDir() string //  Return to a default directory for temporary files 
var Args []string // os.Args Returns an array of strings , The first parameter is the execution file itself 

os Example :

package main

import (
   "fmt"
   "os"
)

func main() {
   //  Predefined variables ,  Save command line arguments 
   fmt.Println(os.Args)
   //  obtain host name
   fmt.Println(os.Hostname())
   fmt.Println(os.Getpid())
   //  Get all environment variables 
   env := os.Environ()
   for k, v := range env {
      fmt.Println(k, v)
   }
   //  To terminate the program 
   // os.Exit(1)
   //  Get an environment variable 
   fmt.Println(os.Getenv("PATH"))
   //  Get current directory 
   dir, err := os.Getwd()
   fmt.Println(dir, err)
   //  Create directory 
   err = os.Mkdir(dir+"/new_file", 0755)
   fmt.Println(err)
   //  Create directory 
   err = os.MkdirAll(dir+"/new", 0755)
   fmt.Println(err)
   //  Delete directory 
   err = os.Remove(dir + "/new_file")
   err = os.Remove(dir + "/new")
   fmt.Println(err)
   //  Create temporary directory 
   tmp_dir := os.TempDir()
   fmt.Println(tmp_dir)
}

3、File Structure

func Create(name string) (file *File, err error) // Create Adopt mode 0666 Create a file called name The file of , If the file already exists, it will be truncated ( Empty file )
func Open(name string) (file *File, err error) // Open Open a file for reading . If the operation is successful , The method of the returned file object can be used to read data 
func (f *File) Stat() (fi FileInfo, err error) // Stat Return to the description file f Of FileInfo Type values 
func (f *File) Readdir(n int) (fi []FileInfo, err error) //  Readdir Read directory f The content of , Return to one with n Of members []FileInfo
func (f *File) Read(b []byte) (n int, err error) // Read Methods from f Read the most len(b) Byte data and write b
func (f *File) WriteString(s string) (ret int, err error) //  Write a string to a file 
func (f *File) Sync() (err error) // Sync The current contents of the submitted documents shall be stored stably 
func (f *File) Close() error // Close Close file f, Make the file unusable for reading and writing 

File Example :

package main

import (
   "fmt"
   "os"
   "time"
)

func main() {
   //  Get current directory 
   dir, err := os.Getwd()
   fmt.Println(dir, err)
   file := dir + "/new"
   var fh *os.File
   fi, _ := os.Stat(file)
   if fi == nil {
      fh, _ = os.Create(file) //  Create files if they don't exist 
   } else {
      fh, _ = os.OpenFile(file, os.O_RDWR, 0666) //  Open as soon as the file exists 
   }
   w := []byte("hello go language" + time.Now().String())
   n, err := fh.Write(w)
   fmt.Println(n, err)
   //  Set the next read / write position 
   ret, err := fh.Seek(0, 0)
   fmt.Printf("%s %v %v\n"," Current file pointer position ", ret, err)
   b := make([]byte, 128)
   n, err = fh.Read(b)
   fmt.Printf("%d %v %s\n",n, err, string(b))
   fh.Close()
}

4、FileInfo Structure

FileInfo Used to describe a file object .

type FileInfo interface {
   Name() string       // base name of the file
   Size() int64        // length in bytes for regular files; system-dependent for others
   Mode() FileMode     // file mode bits
   ModTime() time.Time // modification time
   IsDir() bool        // abbreviation for Mode().IsDir()
   Sys() interface{}   // underlying data source (can return nil)
}

func Stat(name string) (fi FileInfo, err error)

Stat Returns the... Of the description file FileInfo. If the specified file object is a symbolic link , Back to FileInfo Information describing the file to which the symbolic link points , This function will try to jump to the link

func Lstat(name string) (fi FileInfo, err error)

Lstat Returns the... That describes the file object FileInfo. If the specified file object is a symbolic link , Back to FileInfo Information describing the symbolic link , This function does not attempt to jump to the link .

package main

import (
   "os"
)

func main() {
   file := "/home/user/hello.go"
   fi, _ := os.Stat(file)
   if fi == nil {
      fh, _ := os.Create(file) //  Create files if they don't exist 
      fh.Write([]byte("package main\nfunc main(){\n}\n"))
   } else {
      fh, _ := os.OpenFile(file, os.O_RDWR, 0666) //  Open as soon as the file exists 
      fh.Write([]byte("package main\nfunc main(){\n}\n"))
   }
}

Two 、bufio

1、bufio brief introduction

bufio Module through pair io Packaging of modules , Provides data buffering function , It can reduce the cost of large data reading and writing to a certain extent .

stay bufio A buffer is maintained inside each component , Data read and write operations are directly through the cache . When a read-write operation is initiated , Will first try to get data from the buffer ; Only when the buffer has no data , To get the data update buffer from the data source .

2、Reader

type Reader struct {
   buf          []byte
   rd           io.Reader // reader provided by the client
   r, w         int       // buf read and write positions
   err          error
   lastByte     int
   lastRuneSize int
}

Can pass NewReader Function creation bufio.Reader object , Function receives a io.Reader As a parameter . therefore ,bufio.Reader Can't be used directly , Need to be bound to a io.Reader On .

func NewReader(rd io.Reader) *Reader
func NewReaderSize(rd io.Reader, size int) *Reader //  You can configure the size of the buffer 

Compare with io.Reader,bufio.Reader Many practical methods are provided , It can read data more effectively .bufio.Reader Can be right Reader Perform fine-grained operations :

A、Read, Read n individual byte data

B、Discard, Discard the next n individual byte data

C、Peek, Gets the following in the current buffer n individual byte, But don't move the pointer

D、Reset, Clear the entire buffer

func (b *Reader) Read(p []byte) (n int, err error)
func (b *Reader) Discard(n int) (discarded int, err error)
func (b *Reader) Peek(n int) ([]byte, error)
func (b *Reader) Reset(r io.Reader)

bufio.Reader It also provides several methods at higher levels of abstraction for simple structured reading of data , as follows :

A、ReadByte, Read a byte

B、ReadRune, Read a utf-8 character

C、ReadLine, Read a row of data , from ’\n’ Separate

D、ReadBytes, Read a byte list

E、ReadString, Read a string

func (b *Reader) ReadByte() (byte, error)
func (b *Reader) ReadRune() (r rune, size int, err error)
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
func (b *Reader) ReadBytes(delim byte) ([]byte, error)
func (b *Reader) ReadString(delim byte) (string, error)

bufio.Reader Examples of use :

package main

import (
   "strings"
   "fmt"
   "bufio"
)

func main() {
   r := strings.NewReader("hello world !")
   reader := bufio.NewReader(r)

   bytes, _ := reader.Peek(5)
   fmt.Printf("%s\n",bytes)
   n, _ := reader.Read(bytes)
   fmt.Println(n)
   reader.Discard(1)

   for {
      str, err := reader.ReadString(byte(' '))
      fmt.Println(str)
      if err != nil {
         return
      }
   }
}
// output
// hello
// 5
// world
// !

3、Writer

type Writer struct {
   err error
   buf []byte
   n   int
   wr  io.Writer
}



func NewWriter(w io.Writer) *Writer
func NewWriterSize(w io.Writer, size int) *Writer

establish Writer Object's interface

func (b *Writer) Write(p []byte) (nn int, err error) //  write in n byte data 
func (b *Writer) Reset(w io.Writer) //  Reset current buffer 
func (b *Writer) Flush() error //  Clear the current buffer , Write data to output 
func (b *Writer) WriteByte(c byte) error  //  Write a byte 
func (b *Writer) WriteRune(r rune) (size int, err error) //  Write a character 
func (b *Writer) WriteString(s string) (int, error) //  Write a string 

func (b *Writer) Available() int //  How many bytes of space are available in the cache 

func (b *Writer) Buffered() int //  How many bytes have been written to the current cache 

func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) //  Realization io.ReaderFrom

4、ReadWriter

type ReadWriter struct {
   *Reader
   *Writer
}

ReadWriter Realized io.ReadWriter.

func NewReadWriter(r *Reader, w *Writer) *ReadWriter

ReadWriter objects creating

5、Scanner

type Scanner struct {
   r            io.Reader // The reader provided by the client.
   split        SplitFunc // The function to split the tokens.
   maxTokenSize int       // Maximum size of a token; modified by tests.
   token        []byte    // Last token returned by split.
   buf          []byte    // Buffer used as argument to split.
   start        int       // First non-processed byte in buf.
   end          int       // End of data in buf.
   err          error     // Sticky error.
   empties      int       // Count of successive empty tokens.
   scanCalled   bool      // Scan has been called; buffer is in use.
   done         bool      // Scan has finished.
}

Recommended for engineering development Scanner Reading data , Not directly Reader class .Scanner Can pass splitFunc Split the input data into multiple token, Then read in sequence .

func NewScanner(r io.Reader) *Scanner

establish scanner object

func (s *Scanner) Split(split SplitFunc)

Set up scanner The partition function .

In the use of scanner You need to set before splitFunc( The default is ScanLines),splitFunc Used to split input data into multiple token.bufio The module provides several defaults splitFunc, It can meet the needs of most scenarios , Include :

A、ScanBytes, according to byte To break up

B、ScanLines, Follow the line (“\n”) To break up

C、ScanRunes, according to utf-8 Split characters

D、ScanWords, According to the word (” “) To break up

adopt Scanner Of Split Method , It can be for Scanner Appoint splitFunc. How to use it is as follows :

scanner := bufio.NewScanner(os.StdIn)
scanner.split(bufio.ScanWords)

Set the split method

type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

Function takes two parameters , The first parameter is the input data , The second parameter is an identification bit , Used to identify whether the current data is end . The function returns three arguments , The first is this time split Pointer offset of the operation ; The second is the currently read token; The third is the returned error message .

func (s *Scanner) Scan() bool
func (s *Scanner) Text() string
func (s *Scanner) Bytes() []byte

At the completion of Scanner After the initialization , adopt Scan Method can read a forward in the input token, Read successfully and return True; Use Text and Bytes Method to get token,Text Returns a string ,Bytes Returns an array of bytes .

Scanner Examples of use :

package main

import (
   "strings"
   "fmt"
   "bufio"
)

func main() {
   scanner := bufio.NewScanner(strings.NewReader("hello world !"))
   scanner.Split(bufio.ScanWords)
   for scanner.Scan() {
      fmt.Println(scanner.Text())
   }
}
// output
// hello
// world
// !

3、 ... and 、ioutil

1、ioutil brief introduction

ioutil Provide for the right to io Package encapsulation function .

2、ReadAll

func ReadAll(r io.Reader) ([]byte, error)

ReadAll Read r All data in
Return the read data and any errors encountered during reading . If the read is successful , be err return nil, instead of EOF.

s := strings.NewReader("Hello World!")
ra, _ := ioutil.ReadAll(s)
fmt.Printf("%s", ra)
// Hello World!

func ReadFile(filename string) ([]byte, error)

ReadFile Read all the data in the file , Return the read data and any errors encountered during reading . If the read is successful , be err return nil, instead of EOF.

content, err := ioutil.ReadFile("/home/user/hello.txt")
if err != nil {
   log.Fatal(err)
}

fmt.Printf("File contents: %s", content)

3、WriteFile

func WriteFile(filename string, data []byte, perm os.FileMode) error

WriteFile To file filename Middle write data data, If the file doesn't exist , with perm Permission to create the file ; If the file exists , Empty the file first , And then write . Returns any errors encountered during writing .

filename := "/home/user/hello.txt"
data := []byte("Hello World!")
ioutil.WriteFile(filename, data, os.ModeAppend)
contents, _ := ioutil.ReadFile(filename)
fmt.Printf("%s", contents)
// Hello World!

4、ReadDir

func ReadDir(dirname string) ([]os.FileInfo, error)

ReadDir Read directory dirmane All directories and files in ( Exclude subdirectories )
Return the information list of the read file and any errors encountered during reading , The list of returned files is sorted .

rd, err := ioutil.ReadDir("/home/user")
for _, fi := range rd {
   fmt.Println("")
   fmt.Println(fi.Name())
   fmt.Println(fi.IsDir())
   fmt.Println(fi.Size())
   fmt.Println(fi.ModTime())
   fmt.Println(fi.Mode())
}
fmt.Println("")
fmt.Println(err)

5、TempDir

func TempDir(dir, prefix string) (name string, err error)

TempDir Same function TempFile, Just create a directory , The return value only returns the full path of the directory .

content := []byte("temporary file's content")
dir, err := ioutil.TempDir("/home/user", "example")
if err != nil {
   log.Fatal(err)
}

defer os.RemoveAll(dir) // clean up

tmpfn := filepath.Join(dir, "tmpfile")
if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
   log.Fatal(err)
}

6、TempFile

func TempFile(dir, prefix string) (f *os.File, err error)

TempFile In the catalog dir Create a temporary file in and open it , File name to prefix The prefix
Returns the object of the created file and any errors encountered during creation
If dir It's empty , Create a temporary file in the temporary directory of the system
If the system temporary directory is not set in the environment variable , It's in /tmp Create temporary file in
The caller can use f.Name() Method to get the full path of the temporary file
call TempFile Temporary files created , It should be removed by the caller himself

content := []byte("temporary file's content")
tmpfile, err := ioutil.TempFile("/home/user", "example")
if err != nil {
   log.Fatal(err)
}

defer os.Remove(tmpfile.Name()) // clean up

if _, err := tmpfile.Write(content); err != nil {
   log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
   log.Fatal(err)
}

7、Discard

var Discard io.Writer = devNull(0)

Discard It's a io.Writer, Anything done to it Write All calls will succeed unconditionally .devNull The realization of optimization ReadFrom, therefore io.Copy To ioutil.Discard Avoid unnecessary work , So it will be successful . however ioutil.Discard Don't record copy Value obtained .

a := strings.NewReader("hello")
p := make([]byte, 20)
io.Copy(ioutil.Discard, a)
ioutil.Discard.Write(p)
fmt.Println(p)
//[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

8、NopCloser

func NopCloser(r io.Reader) io.ReadCloser

ReadCloser Interfaces combine basic Read and Close Method .NopCloser Will provide Reader r Empty operation Close Method packed as ReadCloser return .

s := strings.NewReader("hello world!")
r := ioutil.NopCloser(s)
r.Close()
p := make([]byte, 10)
r.Read(p)
fmt.Println(string(p))
//hello worl

Four 、bytes

1、bytes brief introduction

bytes Package provides a series of functions to read and write byte slices .  Byte slicing has more functions , It is divided into basic processing functions 、 Comparison function 、 Suffix checking function 、 Index function 、 Partition function 、 Case processing function and sub slice processing function, etc .

strings And bytes The function interface functions of are basically the same .

2、 Basic functions

func Contains(b,subslice []bytes) bool

Check byte slice b Whether it contains sub slices subslice, If include return true, Otherwise return to false.

func Count(s,sep []byte) int

Compute byte slices sep In the byte slice s The number of non overlapping displays in .

func Repeat(b[]byte,count int) []byte

Slice b Copy count individual , Then compose a new byte slice and return .

func Replace(s,old,new []byte,n int) []byte

Returns the byte slice s A copy of , And put the front n Non overlapping sub slices old Replace with new; If n<0, There is no limit on the number of replacements . Parameters n Is the number of times to replace .
 

func Runes(s []byte) []rune

hold s Convert to UTF-8 The sequence of encoded bytes , And return the corresponding Unicode section

func Join(s [][]byte,sep[]byte) []byte

Slice with bytes sep hold s Each byte slice in is concatenated into a byte slice and returns .

Examples of basic functions :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //Contains
   b := []byte("hello") // String strong to byte section 
   sublice1 := []byte("h")
   sublice2 := []byte("l")
   fmt.Println(bytes.Contains(b,sublice1))// true
   fmt.Println(bytes.Contains(b,sublice2))// false

   //Count
   s := []byte("hello world")
   sep1 := []byte("ll")
   sep2 := []byte("l")
   sep3 := []byte("o")
   fmt.Println(bytes.Count(s,sep1))// 1
   fmt.Println(bytes.Count(s,sep2))// 3
   fmt.Println(bytes.Count(s,sep3))// 2

   //Repeat
   b = []byte("hello world")
   fmt.Println(string(bytes.Repeat(b,1)))// hello world
   fmt.Println(string(bytes.Repeat(b,2)))// hello worldhello world

   //Replace
   s = []byte("hello,world")
   old := []byte("o")
   news := []byte("ee")
   fmt.Println(string(bytes.Replace(s,old,news,0)))//hello,world
   fmt.Println(string(bytes.Replace(s,old,news,1)))//hellee,world
   fmt.Println(string(bytes.Replace(s,old,news,2)))//hellee,weerld
   fmt.Println(string(bytes.Replace(s,old,news,-1)))//hellee,weerld

   //Runes
   s = []byte(" Hello world ")
   r := bytes.Runes(s)
   fmt.Println(" Length of string before conversion : ",len(s))//12
   fmt.Println(" Length of converted String : ",len(r))//4

   //Join
   ss := [][]byte{[]byte(" Hello "),[]byte(" The world ")}
   sep4 := []byte(",")
   fmt.Println(string(bytes.Join(ss,sep4)))// Hello , The world 
   sep5 := []byte("#")
   fmt.Println(string(bytes.Join(ss,sep5)))// Hello # The world 
}

3、 Comparison function

func Compare(a,b[]byte) int

Compare byte slices based on byte values a and b Size , If a=b, return 0, If a>b return 1, If a<b return -1.

func Equal(a,b[]byte) bool

Compare 2 Whether the byte slices are equal , If the parameter is nil, Is equivalent to an empty byte slice , If a=b, Then return to true, Otherwise return to false. Case sensitive .

func EqualFold(s,t[]byte) bool

hold s and t convert to UTF-8 String comparison , And ignore case , If s=t, return true, otherwise , return false.

Comparison function example :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //Compare
   a := []byte("hello,go")
   b := []byte("hello,world")
   fmt.Println(bytes.Compare(a,b))//-1
   b =[]byte("hello,c")
   fmt.Println(bytes.Compare(a,b))//1
   b =[]byte("hello,World")
   fmt.Println(bytes.Compare(a,b))//1   Greater than lowercase letters 
   b =[]byte("b")
   fmt.Println(bytes.Compare(a,b))//-1  Compare from the first byte , If the same, compare the length 

   //Equal
   a = []byte("abc")
   b = []byte("ABC")
   fmt.Println(bytes.Equal(a,b))//false
   fmt.Println(bytes.Equal(a,nil))//false
   b = []byte("abc")
   fmt.Println(bytes.Equal(a,b))//true

   //EqualFold
   a = []byte("abc")
   b = []byte("ABC")
   fmt.Println(bytes.EqualFold(a,b))//true
}

4、 Infix check

func HasPrefix(s,prefix[]byte) bool

Check byte slice s Is the prefix of prefix, If it's a return true, If not to return false

func HashSuffix(s,suffix[]byte) bool

Check byte slice s Is the suffix of suffix, If it's a return true, Otherwise return to false.

Examples of infix checks :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //HasPrefix
   s := []byte("test_Hello.txt")
   prefix := []byte("test")
   fmt.Println(bytes.HasPrefix(s,prefix))//true
   prefix = []byte("Test")
   fmt.Println(bytes.HasPrefix(s,prefix))//false

   //HashSuffix
   suffix := []byte("txt")
   fmt.Println(bytes.HasSuffix(s,suffix))//true
}

5、 Location index

The byte slice position index functions share 8 individual ,Index()、IndexAny()、IndexByte()、IndexFunc()、IndexRune()、LastIndex()、LastIndexAny() and LastIndexFunc().

func Index(s,sep []byte) int

return sep stay s The first occurrence of the location index in ( from 0 Start ), If sep Not in s Middle returns -1

func IndexAny(s []byte,chars string) int

hold s It can be interpreted as UTF-8 The sequence of encoded bytes , return chars Any one of the characters in s For the first time
Where the index appears ; If s Contains no chars Any character in , Then return to -1

func IndexByte(s[]byte,c byte) int

Check bytes c stay s The first occurrence of the location index in ; If s Contains no c Then return to -1

func IndexFunc(s[]byte,f func(r rune)bool) int

hold s It can be interpreted as UTF-8 Byte sequence , And return a satisfaction f(c)=true The characters of c The location of
Indexes , If not, it returns -1

func IndexRune(s[]byte,r rune) int

hold s It can be interpreted as UTF-8 Byte sequence , And back to rune Type of characters r stay s Location index in ,
If s Contains no r Then return to -1

func LastIndex(s,sep[]byte) int

return sep stay s The last occurrence of the location index in , If s Contains no sep, Then return to -1

func LastIndexAny(s[]byte,chars string) int

hold s It can be interpreted as UTF-8 Byte sequence , return chars Any one of the characters in s In the end
The location index that appears , If chars Empty or s Contains no chars Any character in , Then return to -1

func LastIndexFunc(s[]byte,f func(r rune)bool) int

hold s It can be interpreted as UTF-8 Byte sequence , Return to satisfaction f(s)=true The characters of c stay s In the end
Location index of one occurrence , Return if not found -1

Location index example :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //Index
   a := []byte("hello,world")
   fmt.Println(bytes.Index(a,[]byte("o")))//4
   fmt.Println(bytes.Index(a,[]byte("ll")))//2
   fmt.Println(bytes.Index(a,[]byte("w")))//6

   //IndexAny
   fmt.Println(bytes.IndexAny(a,"h"))//0
   fmt.Println(bytes.IndexAny(a,"l"))//2

   //IndexByte
   s := []byte("hello,world")
   var ch byte = 'w'
   fmt.Println(bytes.IndexByte(s,ch))//6

   //IndexFunc, Can receive anonymous functions 
   fmt.Println(bytes.IndexFunc(s,func (a rune)bool{
      if a == 'o'{
         return true
      }else{
         return false
      }
   }))//4

   //IndexRune
   fmt.Println(bytes.IndexRune(s,'e'))//1
   fmt.Println(bytes.IndexRune(s,'a'))//-1

   //LastIndex
   fmt.Println(bytes.LastIndex(s,[]byte("g")))//-1
   fmt.Println(bytes.LastIndex(s,[]byte("e")))//1
   fmt.Println(bytes.LastIndex(s,[]byte("o")))//7

   //LastIndexAny
   fmt.Println(bytes.LastIndexAny(s,"world"))//10
   fmt.Println(bytes.LastIndexAny(s,"l"))//9
   fmt.Println(bytes.LastIndexAny(s,"d"))//10

   //LastIndexFunc
   fmt.Println(bytes.LastIndexFunc(s,func(r rune)bool{
      if r=='d'{
         return true
      }else {
         return false
      }
   }))//10
}

6、 Partition function

Byte slice slicing functions share 6 individual ,Fields(),FieldsFunc(),Split(),SplitN(), 
SplitAfter() and SplitAfterN().

func Fields(s[]byte) [][]byte

Slice the bytes s Divide into multiple byte slices according to one or more consecutive white space characters , If s Returns a null byte slice if it contains only white space characters , The parameter s Prepare split byte slice

func FieldsFunc(s []byte,f func(r rune)bool) [][]byte

hold s It can be interpreted as UTF-8 Byte sequence , For each Unicode character c, If f(c) return true Just put c As a split character pair s To break up . If all characters meet f(c) by true, Returns an empty slice

func Split(s,sep[]byte)[][]byte

hold s use sep Split into multiple byte slices and return , If sep It's empty ,Split Then put s Each byte slice corresponds to one UTF-8 character ,Split() The equivalent parameter is n Of splitN() function .

func SplitAfter(s,sep[]byte)[][]byte

Use sep As a suffix, put s Slice into multiple byte slices and return . If sep It's empty , Then put s Each byte slice corresponds to one UTF-8 character .

func SplitAfterN(s,sep[]byte,n int)[][]byte

use sep As a suffix, put s Slice into multiple byte slices and return . If sep It's empty , Then put s Each byte slice corresponds to one UTF-8 character . Parameters n Determine the length of the returned slice : If n>0, Back at most n Sub byte slice , A sub slice may contain an undivided sequence of bytes ; If n=0, Returns an empty slice ; If n< 0, Returns all sub slices .

func SplitN(s,sep []byte,n int)[][]byte

hold s use sep Split into multiple byte slices and return , If sep It's empty ,Split Then put s Each byte slice corresponds to one UTF-8 character , Parameters n Determine the return length ,n>0 Back at most n Sub slice ;
n==0 Returns an empty slice ,n<0 Returns all sub slices .

Split function example :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //Fields , The return is 2 Dimensional section 
   s := []byte("hello world")
   for _,v := range bytes.Fields(s){
      // Traversal access 1 Dimensional section , And then force it into a string 
      fmt.Print(string(v)+",") // hello,world,
   }
   fmt.Println()
   //FieldsFunc, Return is 2 Dimensional section , Receive anonymous function 
   s = []byte("hello,world")
   for _,v := range bytes.FieldsFunc(s,func(r rune)bool{
      if r == ','{
         return true // Split by white space characters 
      }else{
         return false
      }
   }){
      fmt.Print(string(v)+",")// hello,world,
   }
   fmt.Println()
   //Split
   s = []byte(" Tianshan old demon ")
   for _,v := range bytes.Split(s,[]byte(" mountain ")){
      fmt.Print(string(v)+",")// God , Old demon ,
   }
   fmt.Println()
   for _,v := range bytes.Split(s,nil){
      fmt.Print(string(v)+",")// God , mountain , The old , demon ,
   }
   fmt.Println()
   //SplitAfter
   for _,v := range bytes.SplitAfter(s,[]byte(" mountain ")){
      fmt.Print(string(v)+",")// Tianshan mountains , Old demon ,
   }
   fmt.Println()
   for _,v := range bytes.SplitAfter(s,nil){
      fmt.Print(string(v)+",")// God , mountain , The old , demon ,
   }
   fmt.Println()
   //SplitAfterN
   s = []byte("hello,world,hello,go")
   for _,v := range bytes.SplitAfterN(s,[]byte(","),0){
      fmt.Print(string(v)+",") // Output nothing 
   }
   fmt.Println()
   for _,v := range bytes.SplitAfterN(s,[]byte(","),4){
      fmt.Print(string(v))//hello,world,hello,go
   }
   fmt.Println()
   for _,v := range bytes.SplitAfterN(s,[]byte(""),-1){
      fmt.Print(string(v))//hello,world,hello,go
   }
   fmt.Println()
   //SplitN
   s = []byte("hello,world")
   for _,v := range bytes.SplitN(s,[]byte("he"),0){
      fmt.Print(string(v)+",") //
   }
   fmt.Println()
   for _,v := range bytes.SplitN(s,[]byte("o"),3){
      fmt.Print(string(v) + ",")//hell,,w,rld,
   }
   fmt.Println()
   for _,v := range bytes.SplitN(s,[]byte("ll"),-1){
      fmt.Print(string(v)+",")//he,o,world,
   }
}

7、 Case handling functions

share 7 A function ,Title(),ToTitle(),ToTitleSpecial(),ToLower(),ToLowerSpecial(),ToUpper()  and ToUpperSpecial().

func Title(s[]byte) []byte

Return to one s Copy of , hold s Change the first letter of each word in to Unicode Characters are capitalized

func ToTitle(s []byte) []byte

return s A copy of , And put all of them Unicode Character to uppercase

func ToTitleSpecial(_case unicode.SpecialCase,s []byte) []byte

return s A copy of , And put all of them Unicode Characters according to _case The specified rule is capitalized

func ToLower(s []byte)[]byte

return s A copy of , And put all of them Unicode Character to lowercase

func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte

return s A copy of , And put all of them Unicode Characters according to _case The rule of rule is converted to lowercase

func ToUpper(s []byte) []byte

return s A copy of , And put all of them Unicode All characters are capitalized

func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte

return s A copy of , And put all of them Unicode Characters are based on _case The specified rule is capitalized

Case handling function example :

package main

import (
   "fmt"
   "bytes"
   "unicode"
)

func main() {
   s := []byte("hello,go")
   fmt.Println(string(bytes.Title(s)))// Hello,Go
   fmt.Println(string(bytes.ToTitle(s)))// HELLO,GO
   fmt.Println(string(bytes.ToTitleSpecial(unicode.AzeriCase,s)))// HELLO,GO
   s = []byte("Hello,Go")
   fmt.Println(string(bytes.ToLower(s)))// hello,go
   fmt.Println(string(bytes.ToLowerSpecial(unicode.AzeriCase,s)))// hello,go
   s = []byte("Hello,Go")
   fmt.Println(string(bytes.ToUpper(s)))// HELLO,GO
   fmt.Println(string(bytes.ToUpperSpecial(unicode.AzeriCase,s)))// HELLO,GO
}

8、 Sub byte slice handler

The sub byte slice processing functions share 9 individual ,Trim(),TrimFunc(),TrimLeft(),TrimLeftFunc(),TrimRight(),TrimRightFunc(),TrimSpace(),TrimPrefix() and TrimSuffix().

func Trim(s []byte, cutset string) []byte

return s Sub byte slice of ,cutset Any of the s The first and last consecutive characters of the will be deleted .

func TrimFunc(s []byte, f func(r rune) bool) []byte

return s Sub byte slice of , Delete s The connection between the head and the tail is satisfied f(c)=true The characters of c.

func TrimLeft(s []byte, cutset string) []byte

return s Sub byte slice of ,cutset Any of the s The first consecutive character is deleted .

func TrimLeftFunc(s []byte, f func(r rune) bool) []byte

return s A sub byte slice of 、 Delete s The first part continuously satisfies f(c)=true The characters of c.

func TrimRight(s []byte, cutset string) []byte

return s Sub byte slice of ,cutset Any of the s The trailing consecutive characters are deleted .

func TrimRightFunc(s []byte, f func(r rune) bool) []byte

return s A sub byte slice of 、 Delete s The tail is continuous f(c)=true The characters of c

func TrimSpace(s []byte) []byte

return s A sub byte slice of , And delete s Continuous at the beginning and end of a Unicode Blank character .

func TrimPrefix(s, prefix []byte) []byte

return s A sub byte slice of , And delete the prefix prefix Part of

func TrimSuffix(s, suffix []byte) []byte

return s A sub byte slice of , And delete the suffix suffix Part of

Example of a sub byte slice handler :

package main

import (
   "fmt"
   "bytes"
)

func main() {
   //Trim
   s := []byte(" Hello,Go  ")
   fmt.Println(string(bytes.Trim(s," ")))// Hello,Go

   //TrimFunc
   s = []byte("hello world")
   fmt.Println(string(bytes.TrimFunc(s,func(r rune)bool{
      if r=='h' || r=='d'{
         return true
      }else{
         return false
      }
   }))) //ello worl


   s = []byte("hello,worldo")
   fmt.Println(string(bytes.TrimFunc(s,func(r rune)bool{
      if r=='h' || r=='o'{
         return true
      }else{
         return false
      }
   }))) // ello,world

   s = []byte("hello,world")
   fmt.Println(string(bytes.TrimFunc(s,func(r rune)bool{
      if r=='h' && r=='o'{
         return true
      }else{
         return false
      }
   }))) // hello,world

   //TrimLeft
   fmt.Println(string(bytes.TrimLeft(s,"h")))// ello,world
   fmt.Println(string(bytes.TrimLeft(s,"l")))// hello,world

   //TrimLeftFunc
   fmt.Println(string(bytes.TrimLeftFunc(s,func(r rune)bool{
      if r == 'h' || r=='l'{
         return true
      }else{
         return false
      }

   }))) // ello,world

   //TrimRight
   fmt.Println(string(bytes.TrimRight(s,"d")))// hello,worl

   //TrimRightFunc
   fmt.Println(string(bytes.TrimRightFunc(s,func(r rune)bool{
      if r == 'd'{
         return true
      }else{
         return false
      }

   })))// hello,worl

   //TrimSpace
   s = []byte("  hello world   ")
   fmt.Println(string(bytes.TrimSpace(s)))// hello world

   //TrimPrefix
   s = []byte("test_Go")
   fmt.Println(string(bytes.TrimPrefix(s,[]byte("test_"))))// Go
   fmt.Println(string(bytes.TrimPrefix(s,[]byte("Test"))))// test_Go

   //TrimSuffix
   s = []byte("hello.go")
   fmt.Println(string(bytes.TrimSuffix(s,[]byte(".go"))))// hello
   fmt.Println(string(bytes.TrimSuffix(s,[]byte(".cpp"))))// hello.go
}

5、 ... and 、path

1、path brief introduction

path Implemented the function of operating on the path separated by slash .

filepath Package implements file path operation functions compatible with various operating systems

2、path Common interfaces

func IsAbs(path string) bool

Determine whether it is an absolute path

func Split(path string) (dir, file string)

Divide the path into path and file name

func Join(elem ...string) string

Combine multiple strings into one path

func Ext(path string) string

Return the extended part of the path

func Base(path string) string

Return the last element of the path

func Dir(path string) string

Return the directory part of the path

func Clean(path string) string

Return the shortest path of the same directory

func Match(pattern, name string) (matched bool, err error)

Whether the regular matches the path (shell File name match )

package main

import (
   "fmt"
   "path"
)

func main() {
   pt := "~/GoLang"

   //  Determine whether it is an absolute path 
   is_abs := path.IsAbs(pt)
   fmt.Println(is_abs) // false

   //  Divide the path into path and file name 
   pf := "/home/user/hello.go"
   dir, file := path.Split(pf)
   fmt.Println(dir, file) // /home/user/ hello.go

   //  Combine multiple strings into one path 
   dir_join := path.Join("usr", "local", "bin")
   fmt.Println(dir_join) // usr/local/bin

   //  Extension in return path 
   file_ext := path.Ext(pf)
   fmt.Println(file_ext) // .go

   //  Return the last element of the path 
   dir_base := path.Base(pf)
   fmt.Println(dir_base) // hello.go

   //  Return the directory part of the path 
   dir = path.Dir(pf)
   fmt.Println(dir) // /home/user

   //  Return the shortest path of the same directory 
   dir_a := "/usr/../opt/../home/user"
   fmt.Println(path.Clean(dir_a)) // /home/user

   //  Whether the regular matches the path 
   is_match, err := path.Match("*.xml", "a.xml")
   fmt.Println(is_match, err) // true <nil>
}

3、filepath Common interfaces

filepath.Separator

Predefined variables , Represents the path separator /

filepath.ListSeparator

Predefined variables , Represents the environment variable separator :

func Abs(path string) (string, error)

return path Absolute path relative to the current path

func Clean(path string) string

return path Shortest path

func Rel(basepath, targpath string) (string, error)

return targpath relative basepath route

func EvalSymlinks(path string) (string, error)

Returns the path pointed to by the soft chain

func VolumeName(path string) string

Returns the volume name at the front of the path

func ToSlash(path string) string

  Replace the path separator with /

func FromSlash(path string) string

 / Replace with the path separator

func SplitList(path string) []string

Separate paths in environment variables

func Walk(root string, walkFn WalkFunc) error

Traverse root Directory , And call walkFn

package main

import (
   "fmt"
   "os"
   "path/filepath"
)

//  Print path name 
func pathName(path string, info os.FileInfo, err error) error {
   if err != nil {
      return err
   } else {
      fmt.Println(path)
   }
   return nil
}

func main() {
   //  Predefined variables 
   fmt.Println(string(filepath.Separator), string(filepath.ListSeparator))

   //  return path  Absolute path relative to the current path 
   dir := "/home/user/hello.go"
   real_dir, err := filepath.Abs(dir)
   fmt.Println(real_dir, err)

   //  return path  Shortest path 
   dir = "/usr/../etc/../tmp"
   clear_dir := filepath.Clean(dir)
   fmt.Println(clear_dir) // /tmp

   //  return targpath  relative  basepath route 
   basepath, targpath := "/usr/local", "/usr/local/go/bin"
   rel_dir, err := filepath.Rel(basepath, targpath)
   fmt.Println(rel_dir, err) // go/bin <nil>

   //  Returns the path pointed to by the soft chain 
   symlink := "/usr/local"
   real_dir, err = filepath.EvalSymlinks(symlink)
   fmt.Println(real_dir, err) // /usr/local <nil>

   //  Returns the volume name at the front of the path 
   root := "/usr/local/go"
   vol := filepath.VolumeName(root)
   fmt.Println(vol) // ''

   //  Replace the path separator with  `/`
   slash_dir := filepath.ToSlash(root)
   fmt.Println(slash_dir) // /usr/local/go

   //  `/`  Replace with the path separator 
   from_slash := filepath.FromSlash(slash_dir)
   fmt.Println(from_slash) // /usr/local/go

   //  Separate paths in environment variables 
   env_path := "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin"
   env_slice := filepath.SplitList(env_path)
   for k, v := range env_slice {
      fmt.Println(k, v)
   }
   // 0 /usr/local/bin
   // 1 /usr/bin
   // 2 /bin
   // 3 /usr/sbin
   // 4 /sbin
   // 5 /opt/X11/bin
   // 6 /usr/local/go/bin

   //  Traverse  root  Directory , And call  walkFn
   root_dir, err := os.Getwd()
   err = filepath.Walk(root_dir, pathName)
   fmt.Println(err)
}

4、 Directory traversal

Walk(root stirng, walkFn WalkFunc) error

//  Parameters root It can be a file name or a directory name ;walkFn It's a custom function 
func Walk(root string, walkFn WalkFunc) error {

   // obtain root Description information of 
   info, err := os.Lstat(root)
   if err != nil {
      // If there is an error getting the description information , return err Defined by walkFn Function processing 
      err = walkFn(root, nil, err)
   } else {
      // call walk(root, info, walkFn) Function to recursively traverse root
      err = walk(root, info, walkFn)
   }
   if err == SkipDir {
      return nil
   }
   return err
}

Walk Method will traverse root All files under ( contain root) And call... For each directory and file walkFunc Method . Errors that occur when accessing files and directories will pass through error Parameter passed to WalkFunc Method . The file is traversed in lexical order , It usually makes the output more beautiful , But it will also lead to lower efficiency when dealing with very large directories . in addition ,Walk Function does not traverse symbolic links .

type WalkFunc func(path string, info os.FileInfo, err error) 

WalkFunc Is a method type ,Walk The function calls... When traversing a file or directory . When called, pass parameters to path, take Walk Function root As a prefix . take root + The file name or directory name is used as path Pass to WalkFunc function . For example, in "dir" Traverse to... Under the directory "a" file , be path="dir/a";Info yes path File information of the file pointed to . If there is a problem during traversal , Pass in the parameter err Will describe the problem .WalkFunc Function can handle this problem ,Walk We will not drill down into this directory . If the function returns an error ,Walk The function terminates execution ; There is only one exception , We also usually use this to skip some directories . When WalkFunc The return value of filepaht.SkipDir when ,Walk This directory will be skipped , Execute the next file as usual .

func walk(path string, info os.FileInfo, walkFn WalkFunc) error {

   // Call defined walkFn Custom function processing 
   err := walkFn(path, info, nil)
   if err != nil {
      // Returns an error , And the directory can skip 
      if info.IsDir() && err == SkipDir {
         return nil
      }
      return err
   }

   // If it's a file , Then traverse the next 
   if !info.IsDir() {
      return nil
   }

   // Read the path All directories and files under 
   names, err := readDirNames(path)
   if err != nil {
      // An error occurred , Call a custom function to handle 
      return walkFn(path, info, err)
   }

   // Traverse the list of files and directories 
   for _, name := range names {
      // route path/name
      filename := Join(path, name)
      // Get the file or directory information 
      fileInfo, err := lstat(filename)
      if err != nil {
         // An error occurred , Call a custom function to handle 
         if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir {
            return err
         }
      } else {
         // This recursively calls , obtain root File and directory information at all levels , In custom functions walkFn Do it in the kitchen 
         err = walk(filename, fileInfo, walkFn)
         if err != nil {
            // An error occurred while traversing the file or directory and cannot be skipped , Then return to err
            if !fileInfo.IsDir() || err != SkipDir {
               return err
            }
         }
      }
   }
   return nil
}

原网站

版权声明
本文为[Tianshan old demon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011855416568.html