diff --git a/docs/netutil.md b/docs/netutil.md index 275474a..14e0298 100644 --- a/docs/netutil.md +++ b/docs/netutil.md @@ -1,19 +1,21 @@ # Netutil + Package netutil contains functions to get net information and send http request.
## Source: -- [https://github.com/duke-git/lancet/blob/main/netutil/net.go](https://github.com/duke-git/lancet/blob/main/netutil/net.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/net.go](https://github.com/duke-git/lancet/blob/main/netutil/net.go) -- [https://github.com/duke-git/lancet/blob/main/netutil/http_client.go](https://github.com/duke-git/lancet/blob/main/netutil/http_client.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/http_client.go](https://github.com/duke-git/lancet/blob/main/netutil/http_client.go) -- [https://github.com/duke-git/lancet/blob/main/netutil/http.go](https://github.com/duke-git/lancet/blob/main/netutil/http.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/http.go](https://github.com/duke-git/lancet/blob/main/netutil/http.go) ## Usage: + ```go import ( "github.com/duke-git/lancet/v2/netutil" @@ -23,33 +25,34 @@ import ( ## Index -- [ConvertMapToQueryString](#ConvertMapToQueryString) -- [EncodeUrl](#EncodeUrl) -- [GetInternalIp](#GetInternalIp) -- [GetIps](#GetIps) -- [GetMacAddrs](#GetMacAddrs) -- [GetPublicIpInfo](#GetPublicIpInfo) -- [GetRequestPublicIp](#GetRequestPublicIp) -- [IsPublicIP](#IsPublicIP) -- [IsInternalIP](#IsInternalIP) -- [HttpRequest](#HttpRequest) -- [HttpClient](#HttpClient) -- [SendRequest](#SendRequest) -- [DecodeResponse](#DecodeResponse) -- [StructToUrlValues](#StructToUrlValues) -- [HttpGetDeprecated](#HttpGet) -- [HttpDeleteDeprecated](#HttpDelete) -- [HttpPostDeprecated](#HttpPost) -- [HttpPutDeprecated](#HttpPut) -- [HttpPatchDeprecated](#HttpPatch) -- [ParseHttpResponse](#ParseHttpResponse) + +- [ConvertMapToQueryString](#ConvertMapToQueryString) +- [EncodeUrl](#EncodeUrl) +- [GetInternalIp](#GetInternalIp) +- [GetIps](#GetIps) +- [GetMacAddrs](#GetMacAddrs) +- [GetPublicIpInfo](#GetPublicIpInfo) +- [GetRequestPublicIp](#GetRequestPublicIp) +- [IsPublicIP](#IsPublicIP) +- [IsInternalIP](#IsInternalIP) +- [HttpRequest](#HttpRequest) +- [HttpClient](#HttpClient) +- [SendRequest](#SendRequest) +- [DecodeResponse](#DecodeResponse) +- [StructToUrlValues](#StructToUrlValues) +- [HttpGetDeprecated](#HttpGet) +- [HttpDeleteDeprecated](#HttpDelete) +- [HttpPostDeprecated](#HttpPost) +- [HttpPutDeprecated](#HttpPut) +- [HttpPatchDeprecated](#HttpPatch) +- [ParseHttpResponse](#ParseHttpResponse) ## Documentation - ### ConvertMapToQueryString +Convert map to url query string.
Signature: @@ -57,6 +60,7 @@ import ( ```go func ConvertMapToQueryString(param map[string]any) string ``` + Example: ```go @@ -68,20 +72,20 @@ import ( ) func main() { - var m = map[string]any{ - "c": 3, - "a": 1, - "b": 2, - } - qs := netutil.ConvertMapToQueryString(m) + var m = map[string]any{ + "c": 3, + "a": 1, + "b": 2, + } + qs := netutil.ConvertMapToQueryString(m) - fmt.Println(qs) //a=1&b=2&c=3 + // Output: + // a=1&b=2&c=3 } ``` - - ### EncodeUrl +Encode url query string values.
Signature: @@ -89,6 +93,7 @@ func main() { ```go func EncodeUrl(urlStr string) (string, error) ``` + Example: ```go @@ -100,18 +105,22 @@ import ( ) func main() { - urlAddr := "http://www.lancet.com?a=1&b=[2]" - encodedUrl, err := netutil.EncodeUrl(urlAddr) - if err != nil { - fmt.Println(err) - } - fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D + urlAddr := "http://www.lancet.com?a=1&b=[2]" + encodedUrl, err := netutil.EncodeUrl(urlAddr) + + if err != nil { + fmt.Println(err) + } + + fmt.Println(encodedUrl) + + // Output: + // http://www.lancet.com?a=1&b=%5B2%5D } ``` - - ### GetInternalIp +Get internal ip information.
Signature: @@ -119,6 +128,7 @@ func main() { ```go func GetInternalIp() string ``` + Example: ```go @@ -126,21 +136,23 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - internalIp := netutil.GetInternalIp() - ip := net.ParseIP(internalIp) + internalIp := netutil.GetInternalIp() + ip := net.ParseIP(internalIp) - fmt.Println(ip) //192.168.1.9 + fmt.Println(ip) + + // Output: + // 192.168.1.9 } ``` - - ### GetIps +Get all ipv4 list.
Signature: @@ -148,6 +160,7 @@ func main() { ```go func GetIps() []string ``` + Example: ```go @@ -155,19 +168,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ips := netutil.GetIps() - fmt.Println(ips) //[192.168.1.9] + ips := netutil.GetIps() + fmt.Println(ips) + + // Output: + // [192.168.1.9] } ``` - - ### GetMacAddrs +Get all mac addresses list.
Signature: @@ -175,6 +190,7 @@ func main() { ```go func GetMacAddrs() []string { ``` + Example: ```go @@ -182,19 +198,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - addrs := netutil.GetMacAddrs() - fmt.Println(addrs) + macAddrs := netutil.GetMacAddrs() + fmt.Println(macAddrs) + + // Output: + // [18:31:bf:09:d1:56 76:ee:2a:e6:2e:0f 74:ee:2a:e6:2e:0f 74:ee:2a:e6:2e:0f] } ``` - - ### GetPublicIpInfo +Get public ip information.
Signature: @@ -202,20 +220,21 @@ func main() { ```go func GetPublicIpInfo() (*PublicIpInfo, error) type PublicIpInfo struct { - Status string `json:"status"` - Country string `json:"country"` - CountryCode string `json:"countryCode"` - Region string `json:"region"` - RegionName string `json:"regionName"` - City string `json:"city"` - Lat float64 `json:"lat"` - Lon float64 `json:"lon"` - Isp string `json:"isp"` - Org string `json:"org"` - As string `json:"as"` - Ip string `json:"query"` + Status string `json:"status"` + Country string `json:"country"` + CountryCode string `json:"countryCode"` + Region string `json:"region"` + RegionName string `json:"regionName"` + City string `json:"city"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Isp string `json:"isp"` + Org string `json:"org"` + As string `json:"as"` + Ip string `json:"query"` } ``` + Example: ```go @@ -227,18 +246,17 @@ import ( ) func main() { - publicIpInfo, err := netutil.GetPublicIpInfo() - if err != nil { - fmt.Println(err) - } + publicIpInfo, err := netutil.GetPublicIpInfo() + if err != nil { + fmt.Println(err) + } - fmt.Println(publicIpInfo) + fmt.Println(publicIpInfo) } ``` - - ### GetRequestPublicIp +Get http request public ip.
Signature: @@ -246,6 +264,7 @@ func main() { ```go func GetRequestPublicIp(req *http.Request) string ``` + Example: ```go @@ -257,31 +276,25 @@ import ( ) func main() { - ip := "36.112.24.10" + ip := "36.112.24.10" - request1 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Forwarded-For": {ip}, - }, - } - publicIp1 := netutil.GetRequestPublicIp(&request1) - fmt.Println(publicIp1) //36.112.24.10 + request := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Forwarded-For": {ip}, + }, + } + publicIp := netutil.GetRequestPublicIp(&request) - request2 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Real-Ip": {ip}, - }, - } - publicIp2 := netutil.GetRequestPublicIp(&request2) - fmt.Println(publicIp2) //36.112.24.10 + fmt.Println(publicIp) + + // Output: + // 36.112.24.10 } ``` - - ### IsPublicIP +Checks if an ip is public or not.
Signature: @@ -289,6 +302,7 @@ func main() { ```go func IsPublicIP(IP net.IP) bool ``` + Example: ```go @@ -296,23 +310,28 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ip1 := net.ParseIP("192.168.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := netutil.IsPublicIP(net.ParseIP("127.0.0.1")) + ip2 := netutil.IsPublicIP(net.ParseIP("192.168.0.1")) + ip3 := netutil.IsPublicIP(net.ParseIP("36.112.24.10")) - fmt.Println(netutil.IsPublicIP(ip1)) //false - fmt.Println(netutil.IsPublicIP(ip2)) //true + fmt.Println(ip1) + fmt.Println(ip2) + fmt.Println(ip3) + + // Output: + // false + // false + // true } ``` - - - ### IsInternalIP +Checks if an ip is intranet or not.
Signature: @@ -320,6 +339,7 @@ func main() { ```go func IsInternalIP(IP net.IP) bool ``` + Example: ```go @@ -327,35 +347,43 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ip1 := net.ParseIP("127.0.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := netutil.IsInternalIP(net.ParseIP("127.0.0.1")) + ip2 := netutil.IsInternalIP(net.ParseIP("192.168.0.1")) + ip3 := netutil.IsInternalIP(net.ParseIP("36.112.24.10")) - fmt.Println(netutil.IsInternalIP(ip1)) //true - fmt.Println(netutil.IsInternalIP(ip2)) //false + fmt.Println(ip1) + fmt.Println(ip2) + fmt.Println(ip3) + + // Output: + // true + // true + // false } ``` - ### HttpRequest +HttpRequest is a struct used to abstract HTTP request entity.
Signature: ```go type HttpRequest struct { - RawURL string - Method string - Headers http.Header - QueryParams url.Values - FormData url.Values - Body []byte + RawURL string + Method string + Headers http.Header + QueryParams url.Values + FormData url.Values + Body []byte } ``` + Example: ```go @@ -363,48 +391,48 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - header := http.Header{} - header.Add("Content-Type", "multipart/form-data") + header := http.Header{} + header.Add("Content-Type", "multipart/form-data") - postData := url.Values{} - postData.Add("userId", "1") - postData.Add("title", "testItem") + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "testItem") - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos", - Method: "POST", - Headers: header, - FormData: postData, - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos", + Method: "POST", + Headers: header, + FormData: postData, + } } ``` - ### HttpClient +HttpClient is a struct used to send HTTP request. It can be instanced with some configurations or none config.
Signature: ```go type HttpClient struct { - *http.Client - TLS *tls.Config - Request *http.Request - Config HttpClientConfig + *http.Client + TLS *tls.Config + Request *http.Request + Config HttpClientConfig } type HttpClientConfig struct { - SSLEnabled bool - TLSConfig *tls.Config - Compressed bool - HandshakeTimeout time.Duration - ResponseTimeout time.Duration - Verbose bool + SSLEnabled bool + TLSConfig *tls.Config + Compressed bool + HandshakeTimeout time.Duration + ResponseTimeout time.Duration + Verbose bool } func NewHttpClient() *HttpClient @@ -412,6 +440,7 @@ func NewHttpClient() *HttpClient func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient ``` + Example: ```go @@ -419,23 +448,22 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - httpClientCfg := netutil.HttpClientConfig{ - SSLEnabled: true, - HandshakeTimeout:10 * time.Second - } - httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) + httpClientCfg := netutil.HttpClientConfig{ + SSLEnabled: true, + HandshakeTimeout:10 * time.Second + } + httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) } ``` - - ### SendRequest +Use HttpClient to send HTTP request.
Signature: @@ -443,6 +471,7 @@ func main() { ```go func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) ``` + Example: ```go @@ -450,40 +479,45 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + return + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + err = httpClient.DecodeResponse(resp, &todo) + if err != nil { + return + } - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) + + // Output: + // 1 } ``` - - ### DecodeResponse +Decode http response into target object.
Signature: @@ -491,6 +525,7 @@ func main() { ```go func (client *HttpClient) DecodeResponse(resp *http.Response, target any) error ``` + Example: ```go @@ -498,39 +533,45 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + return + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + err = httpClient.DecodeResponse(resp, &todo) + if err != nil { + return + } - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) + + // Output: + // 1 } ``` - ### StructToUrlValues +Convert struct to url values, only convert the field which is exported and has `json` tag.
Signature: @@ -538,6 +579,7 @@ func main() { ```go func StructToUrlValues(targetStruct any) url.Values ``` + Example: ```go @@ -549,24 +591,27 @@ import ( ) func main() { - type TodoQuery struct { - Id int `json:"id"` - UserId int `json:"userId"` - } - todoQuery := TodoQuery{ - Id: 1, - UserId: 2, - } - todoValues := netutil.StructToUrlValues(todoQuery) + type TodoQuery struct { + Id int `json:"id"` + Name string `json:"name"` + } + todoQuery := TodoQuery{ + Id: 1, + Name: "Test", + } + todoValues := netutil.StructToUrlValues(todoQuery) - fmt.Println(todoValues.Get("id")) //1 - fmt.Println(todoValues.Get("userId")) //2 + fmt.Println(todoValues.Get("id")) + fmt.Println(todoValues.Get("name")) + + // Output: + // 1 + // Test } ``` - - ### HttpGet (Deprecated: use SendRequest for replacement) +Send http get request.
Signature: @@ -578,6 +623,7 @@ func main() { // params[3] is http client which type should be http.Client. func HttpGet(url string, params ...any) (*http.Response, error) ``` + Example: ```go @@ -585,30 +631,29 @@ package main import ( "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPost (Deprecated: use SendRequest for replacement) +Send http post request.
Signature: @@ -620,44 +665,44 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPost(url string, params ...any) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, "TestAddToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, "TestAddToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPost(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPost(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPut (Deprecated: use SendRequest for replacement) +Send http put request.
Signature: @@ -669,45 +714,45 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPut(url string, params ...any) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPutToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPutToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPut(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPut(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpDelete (Deprecated: use SendRequest for replacement) +Send http delete request.
Signature: @@ -719,34 +764,34 @@ func main() { // params[3] is http client which type should be http.Client. func HttpDelete(url string, params ...any) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - resp, err := netutil.HttpDelete(url) - if err != nil { - log.Fatal(err) - } + url := "https://jsonplaceholder.typicode.com/todos/1" + resp, err := netutil.HttpDelete(url) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPatch (Deprecated: use SendRequest for replacement) +Send http patch request.
Signature: @@ -758,45 +803,45 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPatch(url string, params ...any) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPatchToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPatchToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPatch(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPatch(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### ParseHttpResponse +Decode http response to specified interface.
Signature: @@ -804,44 +849,44 @@ func main() { ```go func ParseHttpResponse(resp *http.Response, obj any) error ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - toDoResp := &Todo{} - err = netutil.ParseHttpResponse(resp, toDoResp) - if err != nil { - log.Fatal(err) - } + toDoResp := &Todo{} + err = netutil.ParseHttpResponse(resp, toDoResp) + if err != nil { + log.Fatal(err) + } - fmt.Println(toDoResp) + fmt.Println(toDoResp) } ``` - diff --git a/docs/netutil_zh-CN.md b/docs/netutil_zh-CN.md index d55799a..428ca9e 100644 --- a/docs/netutil_zh-CN.md +++ b/docs/netutil_zh-CN.md @@ -1,19 +1,20 @@ # Netutil -netutil网络包支持获取ip地址,发送http请求。 + +netutil 网络包支持获取 ip 地址,发送 http 请求。 ## 源码: -- [https://github.com/duke-git/lancet/blob/main/netutil/net.go](https://github.com/duke-git/lancet/blob/main/netutil/net.go) - -- [https://github.com/duke-git/lancet/blob/main/netutil/http_client.go](https://github.com/duke-git/lancet/blob/main/netutil/http_client.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/net.go](https://github.com/duke-git/lancet/blob/main/netutil/net.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/http_client.go](https://github.com/duke-git/lancet/blob/main/netutil/http_client.go) -- [https://github.com/duke-git/lancet/blob/main/netutil/http.go](https://github.com/duke-git/lancet/blob/main/netutil/http.go) +- [https://github.com/duke-git/lancet/blob/main/netutil/http.go](https://github.com/duke-git/lancet/blob/main/netutil/http.go) ## 用法: + ```go import ( "github.com/duke-git/lancet/v2/netutil" @@ -23,33 +24,34 @@ import ( ## 目录 -- [ConvertMapToQueryString](#ConvertMapToQueryString) -- [EncodeUrl](#EncodeUrl) -- [GetInternalIp](#GetInternalIp) -- [GetIps](#GetIps) -- [GetMacAddrs](#GetMacAddrs) -- [GetPublicIpInfo](#GetPublicIpInfo) -- [GetRequestPublicIp](#GetRequestPublicIp) -- [IsPublicIP](#IsPublicIP) -- [IsInternalIP](#IsInternalIP) -- [HttpRequest](#HttpRequest) -- [HttpClient](#HttpClient) -- [SendRequest](#SendRequest) -- [DecodeResponse](#DecodeResponse) -- [StructToUrlValues](#StructToUrlValues) -- [HttpGetDeprecated](#HttpGet) -- [HttpDeleteDeprecated](#HttpDelete) -- [HttpPostDeprecated](#HttpPost) -- [HttpPutDeprecated](#HttpPut) -- [HttpPatchDeprecated](#HttpPatch) -- [ParseHttpResponse](#ParseHttpResponse) + +- [ConvertMapToQueryString](#ConvertMapToQueryString) +- [EncodeUrl](#EncodeUrl) +- [GetInternalIp](#GetInternalIp) +- [GetIps](#GetIps) +- [GetMacAddrs](#GetMacAddrs) +- [GetPublicIpInfo](#GetPublicIpInfo) +- [GetRequestPublicIp](#GetRequestPublicIp) +- [IsPublicIP](#IsPublicIP) +- [IsInternalIP](#IsInternalIP) +- [HttpRequest](#HttpRequest) +- [HttpClient](#HttpClient) +- [SendRequest](#SendRequest) +- [DecodeResponse](#DecodeResponse) +- [StructToUrlValues](#StructToUrlValues) +- [HttpGetDeprecated](#HttpGet) +- [HttpDeleteDeprecated](#HttpDelete) +- [HttpPostDeprecated](#HttpPost) +- [HttpPutDeprecated](#HttpPut) +- [HttpPatchDeprecated](#HttpPatch) +- [ParseHttpResponse](#ParseHttpResponse) ## 文档 - ### ConvertMapToQueryString +将map转换成http查询字符串.
函数签名: @@ -57,6 +59,7 @@ import ( ```go func ConvertMapToQueryString(param map[string]any) string ``` + 例子: ```go @@ -68,20 +71,22 @@ import ( ) func main() { - var m = map[string]any{ - "c": 3, - "a": 1, - "b": 2, - } - qs := netutil.ConvertMapToQueryString(m) + var m = map[string]any{ + "c": 3, + "a": 1, + "b": 2, + } + qs := netutil.ConvertMapToQueryString(m) - fmt.Println(qs) //a=1&b=2&c=3 + fmt.Println(qs) + + // Output: + // a=1&b=2&c=3 } ``` - - ### EncodeUrl +编码url query string的值
函数签名: @@ -89,6 +94,7 @@ func main() { ```go func EncodeUrl(urlStr string) (string, error) ``` + 例子: ```go @@ -100,19 +106,22 @@ import ( ) func main() { - urlAddr := "http://www.lancet.com?a=1&b=[2]" - encodedUrl, err := netutil.EncodeUrl(urlAddr) - if err != nil { - fmt.Println(err) - } - fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D + urlAddr := "http://www.lancet.com?a=1&b=[2]" + encodedUrl, err := netutil.EncodeUrl(urlAddr) + + if err != nil { + fmt.Println(err) + } + + fmt.Println(encodedUrl) + + // Output: + // http://www.lancet.com?a=1&b=%5B2%5D } ``` - - - ### GetInternalIp +获取内部ip
函数签名: @@ -120,6 +129,7 @@ func main() { ```go func GetInternalIp() string ``` + 例子: ```go @@ -127,20 +137,23 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - internalIp := netutil.GetInternalIp() - ip := net.ParseIP(internalIp) + internalIp := netutil.GetInternalIp() + ip := net.ParseIP(internalIp) - fmt.Println(ip) //192.168.1.9 + fmt.Println(ip) + + // Output: + // 192.168.1.9 } ``` - ### GetIps +获取ipv4地址列表
函数签名: @@ -148,6 +161,7 @@ func main() { ```go func GetIps() []string ``` + 例子: ```go @@ -155,19 +169,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ips := netutil.GetIps() - fmt.Println(ips) //[192.168.1.9] + ips := netutil.GetIps() + fmt.Println(ips) + + // Output: + // [192.168.1.9] } ``` - - ### GetMacAddrs +获取mac地址列
函数签名: @@ -175,6 +191,7 @@ func main() { ```go func GetMacAddrs() []string { ``` + 例子: ```go @@ -182,19 +199,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - addrs := netutil.GetMacAddrs() - fmt.Println(addrs) + macAddrs := netutil.GetMacAddrs() + fmt.Println(macAddrs) + + // Output: + // [18:31:bf:09:d1:56 76:ee:2a:e6:2e:0f 74:ee:2a:e6:2e:0f 74:ee:2a:e6:2e:0f] } ``` - - ### GetPublicIpInfo +获取公网ip信息
函数签名: @@ -202,20 +221,21 @@ func main() { ```go func GetPublicIpInfo() (*PublicIpInfo, error) type PublicIpInfo struct { - Status string `json:"status"` - Country string `json:"country"` - CountryCode string `json:"countryCode"` - Region string `json:"region"` - RegionName string `json:"regionName"` - City string `json:"city"` - Lat float64 `json:"lat"` - Lon float64 `json:"lon"` - Isp string `json:"isp"` - Org string `json:"org"` - As string `json:"as"` - Ip string `json:"query"` + Status string `json:"status"` + Country string `json:"country"` + CountryCode string `json:"countryCode"` + Region string `json:"region"` + RegionName string `json:"regionName"` + City string `json:"city"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Isp string `json:"isp"` + Org string `json:"org"` + As string `json:"as"` + Ip string `json:"query"` } ``` + 例子: ```go @@ -227,18 +247,17 @@ import ( ) func main() { - publicIpInfo, err := netutil.GetPublicIpInfo() - if err != nil { - fmt.Println(err) - } + publicIpInfo, err := netutil.GetPublicIpInfo() + if err != nil { + fmt.Println(err) + } - fmt.Println(publicIpInfo) + fmt.Println(publicIpInfo) } ``` - - ### GetRequestPublicIp +获取http请求ip
函数签名: @@ -246,6 +265,7 @@ func main() { ```go func GetRequestPublicIp(req *http.Request) string ``` + 例子: ```go @@ -257,32 +277,25 @@ import ( ) func main() { - ip := "36.112.24.10" + ip := "36.112.24.10" - request1 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Forwarded-For": {ip}, - }, - } - publicIp1 := netutil.GetRequestPublicIp(&request1) - fmt.Println(publicIp1) //36.112.24.10 + request := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Forwarded-For": {ip}, + }, + } + publicIp := netutil.GetRequestPublicIp(&request) - request2 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Real-Ip": {ip}, - }, - } - publicIp2 := netutil.GetRequestPublicIp(&request2) - fmt.Println(publicIp2) //36.112.24.10 + fmt.Println(publicIp) + + // Output: + // 36.112.24.10 } ``` - - - ### IsPublicIP +判断ip是否是公共ip
函数签名: @@ -290,6 +303,7 @@ func main() { ```go func IsPublicIP(IP net.IP) bool ``` + 例子: ```go @@ -297,22 +311,28 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ip1 := net.ParseIP("192.168.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := netutil.IsPublicIP(net.ParseIP("127.0.0.1")) + ip2 := netutil.IsPublicIP(net.ParseIP("192.168.0.1")) + ip3 := netutil.IsPublicIP(net.ParseIP("36.112.24.10")) - fmt.Println(netutil.IsPublicIP(ip1)) //false - fmt.Println(netutil.IsPublicIP(ip2)) //true + fmt.Println(ip1) + fmt.Println(ip2) + fmt.Println(ip3) + + // Output: + // false + // false + // true } ``` - - ### IsInternalIP +判断ip是否是局域网ip.
函数签名: @@ -320,6 +340,7 @@ func main() { ```go func IsInternalIP(IP net.IP) bool ``` + 例子: ```go @@ -327,35 +348,43 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - ip1 := net.ParseIP("127.0.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := netutil.IsInternalIP(net.ParseIP("127.0.0.1")) + ip2 := netutil.IsInternalIP(net.ParseIP("192.168.0.1")) + ip3 := netutil.IsInternalIP(net.ParseIP("36.112.24.10")) - fmt.Println(netutil.IsInternalIP(ip1)) //true - fmt.Println(netutil.IsInternalIP(ip2)) //false + fmt.Println(ip1) + fmt.Println(ip2) + fmt.Println(ip3) + + // Output: + // true + // true + // false } ``` - ### HttpRequest +HttpRequest用于抽象HTTP请求实体的结构
函数签名: ```go type HttpRequest struct { - RawURL string - Method string - Headers http.Header - QueryParams url.Values - FormData url.Values - Body []byte + RawURL string + Method string + Headers http.Header + QueryParams url.Values + FormData url.Values + Body []byte } ``` + 例子: ```go @@ -363,48 +392,48 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/v2/netutil" ) func main() { - header := http.Header{} - header.Add("Content-Type", "multipart/form-data") + header := http.Header{} + header.Add("Content-Type", "multipart/form-data") - postData := url.Values{} - postData.Add("userId", "1") - postData.Add("title", "testItem") + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "testItem") - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos", - Method: "POST", - Headers: header, - FormData: postData, - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos", + Method: "POST", + Headers: header, + FormData: postData, + } } ``` - ### HttpClient +HttpClient是用于发送HTTP请求的结构体。它可以用一些配置参数或无配置实例化.
函数签名: ```go type HttpClient struct { - *http.Client - TLS *tls.Config - Request *http.Request - Config HttpClientConfig + *http.Client + TLS *tls.Config + Request *http.Request + Config HttpClientConfig } type HttpClientConfig struct { - SSLEnabled bool - TLSConfig *tls.Config - Compressed bool - HandshakeTimeout time.Duration - ResponseTimeout time.Duration - Verbose bool + SSLEnabled bool + TLSConfig *tls.Config + Compressed bool + HandshakeTimeout time.Duration + ResponseTimeout time.Duration + Verbose bool } func NewHttpClient() *HttpClient @@ -412,6 +441,7 @@ func NewHttpClient() *HttpClient func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient ``` + 例子: ```go @@ -419,23 +449,22 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - httpClientCfg := netutil.HttpClientConfig{ - SSLEnabled: true, - HandshakeTimeout:10 * time.Second - } - httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) + httpClientCfg := netutil.HttpClientConfig{ + SSLEnabled: true, + HandshakeTimeout:10 * time.Second + } + httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) } ``` - - ### SendRequest +HttpClient发送http请求
函数签名: @@ -443,6 +472,7 @@ func main() { ```go func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) ``` + 例子: ```go @@ -450,40 +480,45 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + return + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + err = httpClient.DecodeResponse(resp, &todo) + if err != nil { + return + } - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) + + // Output: + // 1 } ``` - - ### DecodeResponse +解析http响应体到目标结构体
函数签名: @@ -491,6 +526,7 @@ func main() { ```go func (client *HttpClient) DecodeResponse(resp *http.Response, target any) error ``` + 例子: ```go @@ -498,39 +534,45 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + return + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + err = httpClient.DecodeResponse(resp, &todo) + if err != nil { + return + } - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) + + // Output: + // 1 } ``` - ### StructToUrlValues +将结构体转为url values, 仅转化结构体导出字段并且包含`json` tag
函数签名: @@ -538,6 +580,7 @@ func main() { ```go func StructToUrlValues(targetStruct any) url.Values ``` + 例子: ```go @@ -549,24 +592,27 @@ import ( ) func main() { - type TodoQuery struct { - Id int `json:"id"` - UserId int `json:"userId"` - } - todoQuery := TodoQuery{ - Id: 1, - UserId: 2, - } - todoValues := netutil.StructToUrlValues(todoQuery) + type TodoQuery struct { + Id int `json:"id"` + Name string `json:"name"` + } + todoQuery := TodoQuery{ + Id: 1, + Name: "Test", + } + todoValues := netutil.StructToUrlValues(todoQuery) - fmt.Println(todoValues.Get("id")) //1 - fmt.Println(todoValues.Get("userId")) //2 + fmt.Println(todoValues.Get("id")) + fmt.Println(todoValues.Get("name")) + + // Output: + // 1 + // Test } ``` - - ### HttpGet (Deprecated: use SendRequest for replacement) +发送http get请求
函数签名: @@ -578,6 +624,7 @@ func main() { // params[3] http client,类型必须是http.Client func HttpGet(url string, params ...any) (*http.Response, error) ``` + 例子: ```go @@ -585,30 +632,29 @@ package main import ( "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPost (Deprecated: use SendRequest for replacement) +发送http post请求
函数签名: @@ -620,44 +666,44 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPost(url string, params ...any) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, "TestAddToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, "TestAddToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPost(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPost(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPut (Deprecated: use SendRequest for replacement) +发送http put请求
函数签名: @@ -669,45 +715,45 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPut(url string, params ...any) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPutToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPutToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPut(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPut(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpDelete (Deprecated: use SendRequest for replacement) +发送http delete请求
函数签名: @@ -719,34 +765,34 @@ func main() { // params[3] http client,类型必须是http.Client func HttpDelete(url string, params ...any) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - resp, err := netutil.HttpDelete(url) - if err != nil { - log.Fatal(err) - } + url := "https://jsonplaceholder.typicode.com/todos/1" + resp, err := netutil.HttpDelete(url) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPatch (Deprecated: use SendRequest for replacement) +发送http patch请求
函数签名: @@ -758,45 +804,45 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPatch(url string, params ...any) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPatchToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPatchToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPatch(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPatch(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### ParseHttpResponse +将http请求响应解码成特定struct值
函数签名: @@ -804,44 +850,44 @@ func main() { ```go func ParseHttpResponse(resp *http.Response, obj any) error ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - toDoResp := &Todo{} - err = netutil.ParseHttpResponse(resp, toDoResp) - if err != nil { - log.Fatal(err) - } + toDoResp := &Todo{} + err = netutil.ParseHttpResponse(resp, toDoResp) + if err != nil { + log.Fatal(err) + } - fmt.Println(toDoResp) + fmt.Println(toDoResp) } ``` - diff --git a/docs/random.md b/docs/random.md index c8923a8..62506b1 100644 --- a/docs/random.md +++ b/docs/random.md @@ -56,8 +56,8 @@ import ( ) func main() { - randBytes := random.RandBytes(4) - fmt.Println(randBytes) + randBytes := random.RandBytes(4) + fmt.Println(randBytes) } ``` @@ -82,8 +82,8 @@ import ( ) func main() { - rInt := random.RandInt(1, 10) - fmt.Println(rInt) + rInt := random.RandInt(1, 10) + fmt.Println(rInt) } ``` @@ -108,8 +108,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //pGWsze + randStr := random.RandString(6) + fmt.Println(randStr) //pGWsze } ``` @@ -134,8 +134,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //PACWGF + randStr := random.RandString(6) + fmt.Println(randStr) //PACWGF } ``` @@ -160,8 +160,8 @@ import ( ) func main() { - randStr := random.RandLower(6) - fmt.Println(randStr) //siqbew + randStr := random.RandLower(6) + fmt.Println(randStr) //siqbew } ``` @@ -186,8 +186,8 @@ import ( ) func main() { - randStr := random.RandNumeral(6) - fmt.Println(randStr) //035172 + randStr := random.RandNumeral(6) + fmt.Println(randStr) //035172 } ``` @@ -212,8 +212,8 @@ import ( ) func main() { - randStr := random.RandNumeralOrLetter(6) - fmt.Println(randStr) //0aW7cQ + randStr := random.RandNumeralOrLetter(6) + fmt.Println(randStr) //0aW7cQ } ``` @@ -238,10 +238,10 @@ import ( ) func main() { - uuid, err := random.UUIdV4() + uuid, err := random.UUIdV4() if err != nil { return } - fmt.Println(uuid) + fmt.Println(uuid) } ``` diff --git a/docs/random_zh-CN.md b/docs/random_zh-CN.md index 90f1b25..7d653c2 100644 --- a/docs/random_zh-CN.md +++ b/docs/random_zh-CN.md @@ -56,8 +56,8 @@ import ( ) func main() { - randBytes := random.RandBytes(4) - fmt.Println(randBytes) + randBytes := random.RandBytes(4) + fmt.Println(randBytes) } ``` @@ -82,8 +82,8 @@ import ( ) func main() { - rInt := random.RandInt(1, 10) - fmt.Println(rInt) + rInt := random.RandInt(1, 10) + fmt.Println(rInt) } ``` @@ -108,8 +108,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //pGWsze + randStr := random.RandString(6) + fmt.Println(randStr) //pGWsze } ``` @@ -134,8 +134,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //PACWGF + randStr := random.RandString(6) + fmt.Println(randStr) //PACWGF } ``` @@ -160,8 +160,8 @@ import ( ) func main() { - randStr := random.RandLower(6) - fmt.Println(randStr) //siqbew + randStr := random.RandLower(6) + fmt.Println(randStr) //siqbew } ``` @@ -186,8 +186,8 @@ import ( ) func main() { - randStr := random.RandNumeral(6) - fmt.Println(randStr) //035172 + randStr := random.RandNumeral(6) + fmt.Println(randStr) //035172 } ``` @@ -212,8 +212,8 @@ import ( ) func main() { - randStr := random.RandNumeralOrLetter(6) - fmt.Println(randStr) //0aW7cQ + randStr := random.RandNumeralOrLetter(6) + fmt.Println(randStr) //0aW7cQ } ``` @@ -238,10 +238,10 @@ import ( ) func main() { - uuid, err := random.UUIdV4() + uuid, err := random.UUIdV4() if err != nil { return } - fmt.Println(uuid) + fmt.Println(uuid) } ``` diff --git a/docs/retry.md b/docs/retry.md index 824bfaf..b6b5641 100644 --- a/docs/retry.md +++ b/docs/retry.md @@ -1,16 +1,17 @@ # Retry + Package retry is for executing a function repeatedly until it was successful or canceled by the context. ## Source: -- [https://github.com/duke-git/lancet/blob/main/retry/retry.go](https://github.com/duke-git/lancet/blob/main/retry/retry.go) - +- [https://github.com/duke-git/lancet/blob/main/retry/retry.go](https://github.com/duke-git/lancet/blob/main/retry/retry.go) ## Usage: + ```go import ( "github.com/duke-git/lancet/v2/retry" @@ -20,18 +21,19 @@ import ( ## Index -- [Context](#Context) -- [Retry](#Retry) -- [RetryFunc](#RetryFunc) -- [RetryDuration](#RetryDuration) -- [RetryTimes](#RetryTimes) + +- [Context](#Context) +- [Retry](#Retry) +- [RetryFunc](#RetryFunc) +- [RetryDuration](#RetryDuration) +- [RetryTimes](#RetryTimes) ## Documentation - ### Context +Set retry context config, can cancel the retry with context.
Signature: @@ -39,43 +41,46 @@ import ( ```go func Context(ctx context.Context) ``` + Example: ```go import ( - "context" - "errors" - "fmt" - "github.com/duke-git/lancet/v2/retry" - "time" + "context" + "errors" + "fmt" + "github.com/duke-git/lancet/v2/retry" + "time" ) func main() { - ctx, cancel := context.WithCancel(context.TODO()) - var number int - increaseNumber := func() error { - number++ - if number > 3 { - cancel() - } - return errors.New("error occurs") - } + ctx, cancel := context.WithCancel(context.TODO()) - err := retry.Retry(increaseNumber, - retry.RetryDuration(time.Microsecond*50), - retry.Context(ctx), - ) + number := 0 + increaseNumber := func() error { + number++ + if number > 3 { + cancel() + } + return errors.New("error occurs") + } - if err != nil { - fmt.Println(err) //retry is cancelled - } + duration := retry.RetryDuration(time.Microsecond*50) + + retry.Retry(increaseNumber, + duration, + retry.Context(ctx), + ) + + fmt.Println(number) + + // Output: + // 4 } ``` - - - ### RetryFunc +Function that retry executes.
Signature: @@ -83,6 +88,7 @@ func main() { ```go type RetryFunc func() error ``` + Example: ```go @@ -96,28 +102,31 @@ import ( ) func main() { - var number int + number := 0 + var increaseNumber retry.RetryFunc = func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + duration := retry.RetryDuration(time.Microsecond*50) - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` - - ### RetryTimes +Set times of retry. Default times is 5.
Signature: @@ -125,6 +134,7 @@ func main() { ```go func RetryTimes(n uint) ``` + Example: ```go @@ -138,26 +148,28 @@ import ( ) func main() { - var number int + number := 0 - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryTimes(2)) + err := retry.Retry(increaseNumber, retry.RetryTimes(2)) if err != nil { - log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 - } + fmt.Println(err) + } + + // Output: + // function main.main.func1 run failed after 2 times retry } ``` - - ### RetryDuration +Set duration of retries. Default duration is 3 second.
Signature: @@ -165,6 +177,7 @@ func main() { ```go func RetryDuration(d time.Duration) ``` + Example: ```go @@ -178,26 +191,31 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + duration := retry.RetryDuration(time.Microsecond*50) + + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` - ### Retry +Executes the retryFunc repeatedly until it was successful or canceled by the context.
Signature: @@ -205,6 +223,7 @@ func main() { ```go func Retry(retryFunc RetryFunc, opts ...Option) error ``` + Example: ```go @@ -218,20 +237,25 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + duration := retry.RetryDuration(time.Microsecond*50) + + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` diff --git a/docs/retry_zh-CN.md b/docs/retry_zh-CN.md index 07cf2c3..361f0b2 100644 --- a/docs/retry_zh-CN.md +++ b/docs/retry_zh-CN.md @@ -1,16 +1,17 @@ # Retry -retry重试执行函数直到函数运行成功或被context cancel。 + +retry 重试执行函数直到函数运行成功或被 context cancel。 ## 源码: -- [https://github.com/duke-git/lancet/blob/main/retry/retry.go](https://github.com/duke-git/lancet/blob/main/retry/retry.go) - +- [https://github.com/duke-git/lancet/blob/main/retry/retry.go](https://github.com/duke-git/lancet/blob/main/retry/retry.go) ## 用法: + ```go import ( "github.com/duke-git/lancet/v2/retry" @@ -20,20 +21,19 @@ import ( ## 目录 -- [Context](#Context) -- [Retry](#Retry) -- [RetryFunc](#RetryFunc) -- [RetryDuration](#RetryDuration) -- [RetryTimes](#RetryTimes) +- [Context](#Context) +- [Retry](#Retry) +- [RetryFunc](#RetryFunc) +- [RetryDuration](#RetryDuration) +- [RetryTimes](#RetryTimes) - -## Document文档 - +## Document 文档 ### Context +设置重试context参数
函数签名: @@ -41,43 +41,46 @@ import ( ```go func Context(ctx context.Context) ``` + 例子: ```go import ( - "context" - "errors" - "fmt" - "lancet-demo/retry" - "time" + "context" + "errors" + "fmt" + "lancet-demo/retry" + "time" ) func main() { - ctx, cancel := context.WithCancel(context.TODO()) - var number int - increaseNumber := func() error { - number++ - if number > 3 { - cancel() - } - return errors.New("error occurs") - } + ctx, cancel := context.WithCancel(context.TODO()) - err := retry.Retry(increaseNumber, - retry.RetryDuration(time.Microsecond*50), - retry.Context(ctx), - ) + number := 0 + increaseNumber := func() error { + number++ + if number > 3 { + cancel() + } + return errors.New("error occurs") + } - if err != nil { - fmt.Println(err) //retry is cancelled - } + duration := retry.RetryDuration(time.Microsecond*50) + + retry.Retry(increaseNumber, + duration, + retry.Context(ctx), + ) + + fmt.Println(number) + + // Output: + // 4 } ``` - - - ### RetryFunc +被重试执行的函数
函数签名: @@ -85,6 +88,7 @@ func main() { ```go type RetryFunc func() error ``` + 例子: ```go @@ -98,27 +102,31 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 + var increaseNumber retry.RetryFunc = func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + duration := retry.RetryDuration(time.Microsecond*50) + + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` - - ### RetryTimes +设置重试次数,默认5
函数签名: @@ -126,6 +134,7 @@ func main() { ```go func RetryTimes(n uint) ``` + 例子: ```go @@ -139,25 +148,28 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 - err := retry.Retry(increaseNumber, retry.RetryTimes(2)) + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } + + err := retry.Retry(increaseNumber, retry.RetryTimes(2)) if err != nil { - log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 - } + fmt.Println(err) + } + + // Output: + // function main.main.func1 run failed after 2 times retry } ``` - - ### RetryDuration +设置重试间隔时间,默认3秒
函数签名: @@ -165,6 +177,7 @@ func main() { ```go func RetryDuration(d time.Duration) ``` + 例子: ```go @@ -178,26 +191,31 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + duration := retry.RetryDuration(time.Microsecond*50) + + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` - ### Retry +重试执行函数retryFunc,直到函数运行成功,或被context停止
函数签名: @@ -205,6 +223,7 @@ func main() { ```go func Retry(retryFunc RetryFunc, opts ...Option) error ``` + 例子: ```go @@ -218,20 +237,25 @@ import ( ) func main() { - var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + number := 0 + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + duration := retry.RetryDuration(time.Microsecond*50) + + err := retry.Retry(increaseNumber, duration) if err != nil { - log.Fatal(err) - } + return + } - fmt.Println(number) //3 + fmt.Println(number) + + // Output: + // 3 } ``` diff --git a/docs/slice.md b/docs/slice.md index e0d6afd..5df24f8 100644 --- a/docs/slice.md +++ b/docs/slice.md @@ -94,17 +94,20 @@ func AppendIfAbsent[T comparable](slice []T, item T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b"} - res1 := slice.AppendIfAbsent(strs, "a") - fmt.Println(res1) //[]string{"a", "b"} + result1 := slice.AppendIfAbsent([]string{"a", "b"}, "b") + result2 := slice.AppendIfAbsent([]string{"a", "b"}, "c") - res2 := slice.AppendIfAbsent(strs, "cannot") - fmt.Println(res2"} + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // [a b] + // [a b c] } ``` @@ -122,13 +125,20 @@ func Contain[T comparable](slice []T, target T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Contain([]string{"a", "b", "c"}, "a") - fmt.Println(res) //true + result1 := slice.Contain([]string{"a", "b", "c"}, "a") + result2 := slice.Contain([]int{1, 2, 3}, 4) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -146,13 +156,20 @@ func ContainSubSlice[T comparable](slice, subSlice []T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) - fmt.Println(res) //true + result1 := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) + result2 := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "d"}) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -170,14 +187,31 @@ func Chunk[T any](slice []T, size int) [][]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "b", "c", "d", "e"} - res := slice.Chunk((arr), 3) - fmt.Println(res) //[][]string{{"a", "b", "c"}, {"d", "e"}} + arr := []string{"a", "b", "c", "d", "e"} + + result1 := slice.Chunk(arr, 1) + result2 := slice.Chunk(arr, 2) + result3 := slice.Chunk(arr, 3) + result4 := slice.Chunk(arr, 4) + result5 := slice.Chunk(arr, 5) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) + + // Output: + // [[a] [b] [c] [d] [e]] + // [[a b] [c d] [e]] + // [[a b c] [d e]] + // [[a b c d] [e]] + // [[a b c d e]] } ``` @@ -195,13 +229,26 @@ func Compact[T comparable](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Compact([]int{0, 1, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + result1 := slice.Compact([]int{0}) + result2 := slice.Compact([]int{0, 1, 2, 3}) + result3 := slice.Compact([]string{"", "a", "b", "0"}) + result4 := slice.Compact([]bool{false, true, true}) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + + // Output: + // [] + // [1 2 3] + // [a b 0] + // [true true] } ``` @@ -219,16 +266,20 @@ func Concat[T any](slice []T, slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.Concat([]int{1, 2, 3}, 4, 5) - fmt.Println(res1) //[]int{1, 2, 3, 4, 5} + result1 := slice.Concat([]int{1, 2}, []int{3, 4}) + result2 := slice.Concat([]string{"a", "b"}, []string{"c"}, []string{"d"}) - res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) - fmt.Println(res2) //[]int{1, 2, 3, 4, 5} + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // [1 2 3 4] + // [a b c d] } ``` @@ -246,15 +297,22 @@ func Count[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 3, 4, 5} + nums := []int{1, 2, 3, 3, 4} - fmt.Println(slice.Count(nums, 1)) //1 - fmt.Println(slice.Count(nums, 3)) //2 + result1 := slice.Count(nums, 1) + result2 := slice.Count(nums, 3) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1 + // 2 } ``` @@ -272,22 +330,26 @@ func CountBy[T any](slice []T, predicate func(index int, item T) bool) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(_, num int) bool { - return (num % 2) == 0 - } + nums := []int{1, 2, 3, 4, 5} - res := slice.CountBy(nums, evenFunc) - fmt.Println(res) //3 + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.CountBy(nums, isEven) + + fmt.Println(result) + + // Output: + // 2 } ``` - ### DifferenceCreates an slice of whose element not included in the other given slice.
@@ -302,16 +364,20 @@ func Difference[T comparable](slice, comparedSlice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} - res := slice.Difference(s1, s2) - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Difference(s1, s2) + + fmt.Println(result) + + // Output: + // [1 2 3] } ``` @@ -329,19 +395,24 @@ func DifferenceBy[T comparable](slice []T, comparedSlice []T, iteratee func(inde ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} - addOne := func(i int, v int) int { - return v + 1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{3, 4, 5} - res := slice.DifferenceBy(s1, s2, addOne) - fmt.Println(res) //[]int{1, 2} + addOne := func(i int, v int) int { + return v + 1 + } + + result := slice.DifferenceBy(s1, s2, addOne) + + fmt.Println(result) + + // Output: + // [1 2] } ``` @@ -359,19 +430,24 @@ func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(value, ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6, 7, 8} - isDouble := func(v1, v2 int) bool { - return v2 == 2*v1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6, 7, 8} - res := slice.DifferenceWith(s1, s2, isDouble) - fmt.Println(res) //[]int{1, 5} + isDouble := func(v1, v2 int) bool { + return v2 == 2*v1 + } + + result := slice.DifferenceWith(s1, s2, isDouble) + + fmt.Println(result) + + // Output: + // [1 5] } ``` @@ -389,17 +465,23 @@ func DeleteAt[T any](slice []T, start int, end ...int) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.DeleteAt([]string{"a", "b", "c", "d", "e"}, 3) - fmt.Println(res1) //[]string{"a", "b", "c", "e"} + result1 := slice.DeleteAt([]string{"a", "b", "c"}, -1) + result2 := slice.DeleteAt([]string{"a", "b", "c"}, 0) + result3 := slice.DeleteAt([]string{"a", "b", "c"}, 0, 2) - res2 := slice.DeleteAt([]string{"a", "b", "c", "d", "e"}, 0, 2) - fmt.Println(res2) //[]string{"c", "d", "e"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + // Output: + // [a b c] + // [b c] + // [c] } ``` @@ -417,19 +499,26 @@ func Drop[T any](slice []T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.Drop([]int{}, 0) - fmt.Println(res1) //[]int{} + result1 := slice.Drop([]string{"a", "b", "c"}, 0) + result2 := slice.Drop([]string{"a", "b", "c"}, 1) + result3 := slice.Drop([]string{"a", "b", "c"}, -1) + result4 := slice.Drop([]string{"a", "b", "c"}, 4) - res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) - fmt.Println(res2) //[]int{2, 3, 4, 5} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) - res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) - fmt.Println(res3) //[]int{1, 2, 3, 4} + // Output: + // [a b c] + // [b c] + // [a b] + // [] } ``` @@ -447,20 +536,24 @@ func Equal[T comparable](slice1, slice2 []T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{1, 2, 3} - slice3 := []int{3, 2, 1} + s1 := []int{1, 2, 3} + s2 := []int{1, 2, 3} + s3 := []int{1, 3, 2} - res1 := slice.Equal(slice1, slice2) - res2 := slice.Equal(slice1, slice3) + result1 := slice.Equal(s1, s2) + result2 := slice.Equal(s1, s3) - fmt.Println(res1) //true - fmt.Println(res2) //false + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -478,21 +571,24 @@ func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) boo ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{2, 4, 6} + s1 := []int{1, 2, 3} + s2 := []int{2, 4, 6} - isDouble := func(a, b int) bool { - return b == a*2 - } + isDouble := func(a, b int) bool { + return b == a*2 + } - res := slice.EqualWith(slice1, slice2, isDouble) + result := slice.EqualWith(s1, s2, isDouble) - fmt.Println(res) //true + fmt.Println(result) + + // Output: + // true } ``` @@ -510,18 +606,23 @@ func Every[T any](slice []T, predicate func(index int, item T) bool) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} - res := slice.Every(nums, isEven) - fmt.Println(res) //false + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Every(nums, isEven) + + fmt.Println(result) + + // Output: + // false } ``` @@ -539,18 +640,23 @@ func Filter[T any](slice []T, predicate func(index int, item T) bool) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res := slice.Filter(nums, isEven) - fmt.Println(res) //[]int{2, 4} + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Filter(nums, isEven) + + fmt.Println(result) + + // Output: + // [2 4] } ``` @@ -568,19 +674,25 @@ func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res, ok := slice.Find(nums, even) - fmt.Println(res) //2 - fmt.Println(ok) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result, ok := slice.Find(nums, isEven) + + fmt.Println(*result) + fmt.Println(ok) + + // Output: + // 2 + // true } ``` @@ -598,19 +710,25 @@ func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, boo ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res, ok := slice.FindLast(nums, even) - fmt.Println(res) //4 - fmt.Println(ok) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result, ok := slice.FindLast(nums, isEven) + + fmt.Println(*result) + fmt.Println(ok) + + // Output: + // 4 + // true } ``` @@ -628,14 +746,19 @@ func Flatten(slice any) any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.Flatten(arr) - fmt.Println(res) //{{"a", "b"}, {"c", "d"}} + arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + + result := slice.Flatten(arrs) + + fmt.Println(result) + + // Output: + // [[a b] [c d]] } ``` @@ -653,14 +776,19 @@ func FlattenDeep(slice any) any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.FlattenDeep(arr) - fmt.Println(res) //{"a", "b", "c", "d"} + arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + + result := slice.FlattenDeep(arrs) + + fmt.Println(result) + + // Output: + // [a b c d] } ``` @@ -678,17 +806,24 @@ func ForEach[T any](slice []T, iteratee func(index int, item T)) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 2, 3, 4, 5} - var numbersAddTwo []int - slice.ForEach(numbers, func(index int, value int) { - numbersAddTwo = append(numbersAddTwo, value+2) - }) - fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} + nums := []int{1, 2, 3} + + var result []int + addOne := func(_ int, v int) { + result = append(result, v+1) + } + + slice.ForEach(nums, addOne) + + fmt.Println(result) + + // Output: + // [2 3 4] } ``` @@ -706,19 +841,25 @@ func GroupBy[T any](slice []T, groupFn func(index int, item T) bool) ([]T, []T) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } - even, odd := slice.GroupBy(nums, evenFunc) + nums := []int{1, 2, 3, 4, 5} - fmt.Println(even) //[]int{2, 4, 6} - fmt.Println(odd) //]int{1, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } + + even, odd := slice.GroupBy(nums, isEven) + + fmt.Println(even) + fmt.Println(odd) + + // Output: + // [2 4] + // [1 3 5] } ``` @@ -736,18 +877,23 @@ func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []float64{6.1, 4.2, 6.3} - floor := func(num float64) float64 { - return math.Floor(num) - } - res := slice.GroupWith(nums, floor) - - fmt.Println(res) //map[float64][]float64{ 4: {4.2}, 6: {6.1, 6.3},} + nums := []float64{6.1, 4.2, 6.3} + + floor := func(num float64) float64 { + return math.Floor(num) + } + + result := slice.GroupWith(nums, floor) //map[float64][]float64 + + fmt.Println(result) + + // Output: + // map[4:[4.2] 6:[6.1 6.3]] } ``` @@ -765,14 +911,18 @@ func IntSlice(slice any) []int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var nums = []any{1, 2, 3} - res := slice.IntSlice(nums) - fmt.Println(res) //[]int{1, 2, 3} + nums := []interface{}{1, 2, 3} + + result := slice.IntSlice(nums) //[]int{1, 2, 3} + fmt.Println(result) + + // Output: + // [1 2 3] } ``` @@ -790,14 +940,18 @@ func InterfaceSlice(slice any) []any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var nums = []int{}{1, 2, 3} - res := slice.InterfaceSlice(nums) - fmt.Println(res) //[]any{1, 2, 3} + strs := []string{"a", "b", "c"} + + result := slice.InterfaceSlice(strs) //[]interface{}{"a", "b", "c"} + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -815,16 +969,20 @@ func Intersection[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 2, 3} - s2 := []int{1, 2, 3, 4} - res := slice.Intersection(s1, s2), + nums1 := []int{1, 2, 3} + nums2 := []int{2, 3, 4} - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Intersection(nums1, nums2) + + fmt.Println(result) + + // Output: + // [2 3] } ``` @@ -842,18 +1000,29 @@ func InsertAt[T any](slice []T, index int, value any) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s := []string{"a", "b", "c"} + result1 := slice.InsertAt([]string{"a", "b", "c"}, 0, "1") + result2 := slice.InsertAt([]string{"a", "b", "c"}, 1, "1") + result3 := slice.InsertAt([]string{"a", "b", "c"}, 2, "1") + result4 := slice.InsertAt([]string{"a", "b", "c"}, 3, "1") + result5 := slice.InsertAt([]string{"a", "b", "c"}, 0, []string{"1", "2", "3"}) - res1, _ := slice.InsertAt(s, 0, "1") - fmt.Println(res1) //[]string{"1", "a", "b", "c"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) - res2, _ := slice.InsertAt(s, 3, []string{"1", "2", "3"}) - fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} + // Output: + // [1 a b c] + // [a 1 b c] + // [a b 1 c] + // [a b c 1] + // [1 2 3 a b c] } ``` @@ -871,17 +1040,22 @@ func IndexOf[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.IndexOf(arr, "a") - fmt.Println(res1) //0 + strs := []string{"a", "a", "b", "c"} - res2 := slice.IndexOf(arr, "d") - fmt.Println(res2) //-1 + result1 := slice.IndexOf(strs, "a") + result2 := slice.IndexOf(strs, "d") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 0 + // -1 } ``` @@ -899,17 +1073,22 @@ func LastIndexOf[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.LastIndexOf(arr, "a") - fmt.Println(res1) //1 + strs := []string{"a", "a", "b", "c"} - res2 := slice.LastIndexOf(arr, "d") - fmt.Println(res2) //-1 + result1 := slice.LastIndexOf(strs, "a") + result2 := slice.LastIndexOf(strs, "d") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1 + // -1 } ``` @@ -927,21 +1106,26 @@ func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - multiplyTwo := func(i, num int) int { - return num * 2 - } - res := slice.Map(nums, multiplyTwo) - fmt.Println(res) //[]int{2, 4, 6, 8} + nums := []int{1, 2, 3} + + addOne := func(_ int, v int) int { + return v + 1 + } + + result := slice.Map(nums, addOne) + + fmt.Println(result) + + // Output: + // [2 3 4] } ``` - ### MergeMerge all given slices into one slice.
@@ -956,21 +1140,23 @@ func Merge[T any](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3} - s2 := []int{2, 4} - res := slice.Merge(s1, s2) + nums1 := []int{1, 2, 3} + nums2 := []int{3, 4} - fmt.Println(res) //[]int{1, 2, 3, 2, 4} + result := slice.Merge(nums1, nums2) + + fmt.Println(result) + + // Output: + // [1 2 3 3 4] } ``` - - ### ReverseReverse the elements order in slice.
@@ -985,14 +1171,19 @@ func Reverse[T any](slice []T) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - slice.Reverse(nums) - fmt.Println(res) //[]int{4, 3, 2, 1} + strs := []string{"a", "b", "c", "d"} + + slice.Reverse(strs) + + fmt.Println(strs) + + // Output: + // [d c b a] } ``` @@ -1010,17 +1201,23 @@ func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initia ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - reduceFunc := func(i, v1, v2 int) int { - return v1 + v2 - } - res := slice.Reduce(nums, reduceFunc, 0) - fmt.Println(res) //10 + nums := []int{1, 2, 3} + + sum := func(_ int, v1, v2 int) int { + return v1 + v2 + } + + result := slice.Reduce(nums, sum, 0) + + fmt.Println(result) + + // Output: + // 6 } ``` @@ -1038,18 +1235,31 @@ func Replace[T comparable](slice []T, old T, new T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b", "a", "c", "d", "a"} + strs := []string{"a", "b", "c", "a"} - fmt.Println(slice.Replace(strs, "a", "x", 0)) //{"a", "b", "a", "c", "d", "a"} + result1 := slice.Replace(strs, "a", "x", 0) + result2 := slice.Replace(strs, "a", "x", 1) + result3 := slice.Replace(strs, "a", "x", 2) + result4 := slice.Replace(strs, "a", "x", 3) + result5 := slice.Replace(strs, "a", "x", -1) - fmt.Println(slice.Replace(strs, "a", "x", 1)) //{"x", "b", "a", "c", "d", "a"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) - fmt.Println(slice.Replace(strs, "a", "x", -1)) //{"x", "b", "x", "c", "d", "x"} + // Output: + // [a b c a] + // [x b c a] + // [x b c x] + // [x b c x] + // [x b c x] } ``` @@ -1067,20 +1277,20 @@ func ReplaceAll[T comparable](slice []T, old T, new T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b", "a", "c", "d", "a"} + result := slice.ReplaceAll([]string{"a", "b", "c", "a"}, "a", "x") - fmt.Println(slice.ReplaceAll(strs, "a", "x")) //{"x", "b", "x", "c", "d", "x"} + fmt.Println(result) - fmt.Println(slice.Replace(strs, "e", "x")) //{"a", "b", "a", "c", "d", "a"} + // Output: + // [x b c x] } ``` - ### RepeatCreates a slice with length n whose elements are passed param item.
@@ -1095,16 +1305,20 @@ func Repeat[T any](item T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - fmt.Println(slice.Repeat("a", 3)) //[]string{"a", "a", "a"} + result := slice.Repeat("a", 3) + + fmt.Println(result) + + // Output: + // [a a a] } ``` - ### ShuffleCreates an slice of shuffled values.
@@ -1119,14 +1333,18 @@ func Shuffle[T any](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5} - res := slice.Shuffle(nums) - fmt.Println(res) //3,1,5,4,2 + nums := []int{1, 2, 3, 4, 5} + result := slice.Shuffle(nums) + + fmt.Println(res) + + // Output: + // [3 1 5 4 2] (random order) } ``` @@ -1145,30 +1363,29 @@ func Sort[T constraints.Ordered](slice []T, sortOrder ...string) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 4, 3, 2, 5} - - slice.Sort(numbers) - fmt.Println(numbers) //{1,2,3,4,5} + numbers := []int{1, 4, 3, 2, 5} - slice.Sort(numbers, "desc") - fmt.Println(numbers) //{5,4,3,2,1} + slice.Sort(numbers) + fmt.Println(numbers) // [1 2 3 4 5] - strings := []string{"a", "d", "c", "b", "e"} + slice.Sort(numbers, "desc") + fmt.Println(numbers) // [5 4 3 2 1] - slice.Sort(strings) - fmt.Println(strings) //{"a", "b", "c", "d", "e"} + strings := []string{"a", "d", "c", "b", "e"} - slice.Sort(strings, "desc") - fmt.Println(strings) //{"e", "d", "c", "b", "a"} + slice.Sort(strings) + fmt.Println(strings) //[a b c d e} + + slice.Sort(strings, "desc") + fmt.Println(strings) //[e d c b a] } ``` - ### SortBySorts the slice in ascending order as determined by the less function. This sort is not guaranteed to be stable.
@@ -1183,40 +1400,39 @@ func SortBy[T any](slice []T, less func(a, b T) bool) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 4, 3, 2, 5} + numbers := []int{1, 4, 3, 2, 5} - slice.SortBy(numbers, func(a, b int) bool { - return a < b - }) - fmt.Println(numbers) //{1, 2, 3, 4, 5} + slice.SortBy(numbers, func(a, b int) bool { + return a < b + }) + fmt.Println(numbers) // [1 2 3 4 5] - type User struct { - Name string - Age uint - } + type User struct { + Name string + Age uint + } - users := []User{ - {Name: "a", Age: 21}, - {Name: "b", Age: 15}, - {Name: "c", Age: 100}} + users := []User{ + {Name: "a", Age: 21}, + {Name: "b", Age: 15}, + {Name: "c", Age: 100}} - slice.SortBy(users, func(a, b User) bool { - return a.Age < b.Age - }) + slice.SortBy(users, func(a, b User) bool { + return a.Age < b.Age + }) - fmt.Printf("sort users by age: %v", users) + fmt.Printf("sort users by age: %v", users) - // output - // [{b 15} {a 21} {c 100}] + // output + // [{b 15} {a 21} {c 100}] } ``` - ### SortByField (Deprecated: use Sort and SortBy for replacement)
Sort struct slice by field. Slice element should be struct, field type should be int, uint, string, or bool. Default sort type is ascending (asc), if descending order, set sortType to desc
@@ -1231,32 +1447,30 @@ func SortByField(slice any, field string, sortType ...string) error ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - type student struct { - name string - age int - } - students := []student{ - {"a", 10}, - {"b", 15}, - {"c", 5}, - {"d", 6}, - } - err := slice.SortByField(students, "age", "desc") - if err != nil { - fmt.Println(err) - } - fmt.Println(students) - // []students{ - // {"b", 15}, - // {"a", 10}, - // {"d", 6}, - // {"c", 5}, - // } + type User struct { + Name string + Age uint + } + + users := []User{ + {Name: "a", Age: 21}, + {Name: "b", Age: 15}, + {Name: "c", Age: 100}} + + err := slice.SortByField(users, "Age", "desc") + if err != nil { + return + } + + fmt.Println(users) + + // Output: + // [{c 100} {a 21} {b 15}] } ``` @@ -1274,18 +1488,23 @@ func Some[T any](slice []T, predicate func(index int, item T) bool) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} - res := slice.Some(nums, isEven) - fmt.Println(res) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Some(nums, isEven) + + fmt.Println(result) + + // Output: + // true } ``` @@ -1303,14 +1522,18 @@ func StringSlice(slice any) []string ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var s = []any{"a", "b", "c"} - res := slice.StringSlice(s) - fmt.Println(res) //[]string{"a", "b", "c"} + strs := []interface{}{"a", "b", "c"} + + result := slice.StringSlice(strs) //[]string{"a", "b", "c"} + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -1328,18 +1551,20 @@ func SymmetricDifference[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3} - s2 := []int{1, 2, 4} - s3 := []int{1, 2, 3, 5} + nums1 := []int{1, 2, 3} + nums2 := []int{1, 2, 4} - fmt.Println(slice.SymmetricDifference(s1)) //[]int{1, 2, 3} - fmt.Println(slice.SymmetricDifference(s1, s2)) //[]int{3, 4} - fmt.Println(slice.SymmetricDifference(s1, s2, s3)) //[]int{3, 4, 5} + result := slice.SymmetricDifference(nums1, nums2) + + fmt.Println(result) + + // Output: + // [3 4] } ``` @@ -1357,13 +1582,17 @@ func ToSlice[T any](items ...T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.ToSlice("a", "b") - fmt.Println(res) //{"a", "b"} + result := slice.ToSlice("a", "b", "c") + + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -1381,15 +1610,24 @@ func ToSlicePointer[T any](items ...T) []*T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - str1 := "a" - str2 := "b" - res := slice.ToSlicePointer(str1, str2) - fmt.Println(res) // res -> []*string{&str1, &str2} + str1 := "a" + str2 := "b" + + result := slice.ToSlicePointer(str1, str2) + + expect := []*string{&str1, &str2} + + isEqual := reflect.DeepEqual(result, expect) + + fmt.Println(isEqual) + + // Output: + // true } ``` @@ -1407,13 +1645,16 @@ func Unique[T comparable](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Unique([]int{1, 2, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Unique([]string{"a", "a", "b"}) + fmt.Println(result) + + // Output: + // [a b] } ``` @@ -1431,15 +1672,20 @@ func UniqueBy[T comparable](slice []T, iteratee func(item T) T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { - return val % 4 - }) - fmt.Println(res) //[]int{1, 2, 3, 0} + nums := []int{1, 2, 3, 4, 5, 6} + result := slice.UniqueBy(nums, func(val int) int { + return val % 3 + }) + + fmt.Println(result) + + // Output: + // [1 2 0] } ``` @@ -1457,16 +1703,20 @@ func Union[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 3, 4, 6} - s2 := []int{1, 2, 5, 6} - res := slice.Union(s1, s2) + nums1 := []int{1, 3, 4, 6} + nums2 := []int{1, 2, 5, 6} - fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} + result := slice.Union(nums1, nums2) + + fmt.Println(result) + + // Output: + // [1 3 4 6 2 5] } ``` @@ -1484,16 +1734,22 @@ func UnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - testFunc := func(i int) int { - return i / 2 - } - result := slice.UnionBy(testFunc, []int{0, 1, 2, 3, 4, 5}, []int{0, 2, 10}) - fmt.Println(result) //[]int{0, 2, 4, 10} + nums := []int{1, 2, 3, 4} + + divideTwo := func(n int) int { + return n / 2 + } + result := slice.UnionBy(divideTwo, nums) + + fmt.Println(result) + + // Output: + // [1 2 4] } ``` @@ -1511,15 +1767,29 @@ func UpdateAt[T any](slice []T, index int, value T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s := []string{"a", "b", "c"} + result1 := slice.UpdateAt([]string{"a", "b", "c"}, -1, "1") + result2 := slice.UpdateAt([]string{"a", "b", "c"}, 0, "1") + result3 := slice.UpdateAt([]string{"a", "b", "c"}, 1, "1") + result4 := slice.UpdateAt([]string{"a", "b", "c"}, 2, "1") + result5 := slice.UpdateAt([]string{"a", "b", "c"}, 3, "1") - res1, _ := slice.UpdateAt(s, 0, "1") - fmt.Println(res1) //[]string{"1", "b", "c"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) + + // Output: + // [a b c] + // [1 b c] + // [a 1 c] + // [a b 1] + // [a b c] } ``` @@ -1537,13 +1807,17 @@ func Without[T comparable](slice []T, items ...T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) - fmt.Println(res) //[]int{3, 4, 5} + result := slice.Without([]int{1, 2, 3, 4}, 1, 2) + + fmt.Println(result) + + // Output: + // [3 4] } ``` @@ -1561,15 +1835,18 @@ func KeyBy[T any, U comparable](slice []T, iteratee func(item T) U) map[U]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.KeyBy([]string{"a", "ab", "abc"}, func(str string) int { - return len(str) - }) + result := slice.KeyBy([]string{"a", "ab", "abc"}, func(str string) int { + return len(str) + }) - fmt.Println(res) //map[int]string{1: "a", 2: "ab", 3: "abc"} + fmt.Println(result) + + // Output: + // map[1:a 2:ab 3:abc] } ``` diff --git a/docs/slice_zh-CN.md b/docs/slice_zh-CN.md index a3eb098..8a9d5a6 100644 --- a/docs/slice_zh-CN.md +++ b/docs/slice_zh-CN.md @@ -20,10 +20,8 @@ import ( - ## 目录 - - [AppendIfAbsent](#AppendIfAbsent) - [Contain](#Contain) - [ContainSubSlice](#ContainSubSlice) @@ -78,7 +76,6 @@ import ( - [Without](#Without) - [KeyBy](#KeyBy) - ## 文档 @@ -97,17 +94,20 @@ func AppendIfAbsent[T comparable](slice []T, item T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b"} - res1 := slice.AppendIfAbsent(strs, "a") - fmt.Println(res1) //[]string{"a", "b"} + result1 := slice.AppendIfAbsent([]string{"a", "b"}, "b") + result2 := slice.AppendIfAbsent([]string{"a", "b"}, "c") - res2 := slice.AppendIfAbsent(strs, "cannot") - fmt.Println(res2"} + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // [a b] + // [a b c] } ``` @@ -125,13 +125,20 @@ func Contain[T comparable](slice []T, target T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Contain([]string{"a", "b", "c"}, "a") - fmt.Println(res) //true + result1 := slice.Contain([]string{"a", "b", "c"}, "a") + result2 := slice.Contain([]int{1, 2, 3}, 4) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -149,13 +156,20 @@ func ContainSubSlice[T comparable](slice, subSlice []T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) - fmt.Println(res) //true + result1 := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) + result2 := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "d"}) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -173,14 +187,31 @@ func Chunk[T any](slice []T, size int) [][]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "b", "c", "d", "e"} - res := slice.Chunk(arr, 3) - fmt.Println(res) //[][]string{{"a", "b", "c"}, {"d", "e"}} + arr := []string{"a", "b", "c", "d", "e"} + + result1 := slice.Chunk(arr, 1) + result2 := slice.Chunk(arr, 2) + result3 := slice.Chunk(arr, 3) + result4 := slice.Chunk(arr, 4) + result5 := slice.Chunk(arr, 5) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) + + // Output: + // [[a] [b] [c] [d] [e]] + // [[a b] [c d] [e]] + // [[a b c] [d e]] + // [[a b c d] [e]] + // [[a b c d e]] } ``` @@ -198,13 +229,26 @@ func Compact[T comparable](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Compact([]int{0, 1, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + result1 := slice.Compact([]int{0}) + result2 := slice.Compact([]int{0, 1, 2, 3}) + result3 := slice.Compact([]string{"", "a", "b", "0"}) + result4 := slice.Compact([]bool{false, true, true}) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + + // Output: + // [] + // [1 2 3] + // [a b 0] + // [true true] } ``` @@ -222,16 +266,20 @@ func Concat[T any](slice []T, slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.Concat([]int{1, 2, 3}, 4, 5) - fmt.Println(res1) //[]int{1, 2, 3, 4, 5} + result1 := slice.Concat([]int{1, 2}, []int{3, 4}) + result2 := slice.Concat([]string{"a", "b"}, []string{"c"}, []string{"d"}) - res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) - fmt.Println(res2) //[]int{1, 2, 3, 4, 5} + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // [1 2 3 4] + // [a b c d] } ``` @@ -249,15 +297,22 @@ func Count[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 3, 4, 5} + nums := []int{1, 2, 3, 3, 4} - fmt.Println(slice.Count(nums, 1)) //1 - fmt.Println(slice.Count(nums, 3)) //2 + result1 := slice.Count(nums, 1) + result2 := slice.Count(nums, 3) + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1 + // 2 } ``` @@ -275,18 +330,23 @@ func CountBy[T any](slice []T, predicate func(index int, item T) bool) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(_, num int) bool { - return (num % 2) == 0 - } + nums := []int{1, 2, 3, 4, 5} - res := slice.CountBy(nums, evenFunc) - fmt.Println(res) //3 + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.CountBy(nums, isEven) + + fmt.Println(result) + + // Output: + // 2 } ``` @@ -304,16 +364,20 @@ func Difference[T comparable](slice, comparedSlice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} - res := slice.Difference(s1, s2) - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Difference(s1, s2) + + fmt.Println(result) + + // Output: + // [1 2 3] } ``` @@ -331,19 +395,24 @@ func DifferenceBy[T comparable](slice []T, comparedSlice []T, iteratee func(inde ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} - addOne := func(i int, v int) int { - return v + 1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{3, 4, 5} - res := slice.DifferenceBy(s1, s2, addOne) - fmt.Println(res) //[]int{1, 2} + addOne := func(i int, v int) int { + return v + 1 + } + + result := slice.DifferenceBy(s1, s2, addOne) + + fmt.Println(result) + + // Output: + // [1 2] } ``` @@ -361,19 +430,24 @@ func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(value, ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6, 7, 8} - isDouble := func(v1, v2 int) bool { - return v2 == 2*v1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6, 7, 8} - res := slice.DifferenceWith(s1, s2, isDouble) - fmt.Println(res) //[]int{1, 5} + isDouble := func(v1, v2 int) bool { + return v2 == 2*v1 + } + + result := slice.DifferenceWith(s1, s2, isDouble) + + fmt.Println(result) + + // Output: + // [1 5] } ``` @@ -391,16 +465,23 @@ func DeleteAt[T any](slice []T, start int, end ...int) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.DeleteAt([]string{"a", "b", "c", "d", "e"}, 3) - fmt.Println(res1) //[]string{"a", "b", "c", "e"} + result1 := slice.DeleteAt([]string{"a", "b", "c"}, -1) + result2 := slice.DeleteAt([]string{"a", "b", "c"}, 0) + result3 := slice.DeleteAt([]string{"a", "b", "c"}, 0, 2) - res2 := slice.DeleteAt([]string{"a", "b", "c", "d", "e"}, 0, 2) - fmt.Println(res2) //[]string{"c", "d", "e"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + + // Output: + // [a b c] + // [b c] + // [c] } ``` @@ -419,19 +500,26 @@ func Drop[T any](slice []T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res1 := slice.Drop([]int{}, 0) - fmt.Println(res1) //[]int{} + result1 := slice.Drop([]string{"a", "b", "c"}, 0) + result2 := slice.Drop([]string{"a", "b", "c"}, 1) + result3 := slice.Drop([]string{"a", "b", "c"}, -1) + result4 := slice.Drop([]string{"a", "b", "c"}, 4) - res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) - fmt.Println(res2) //[]int{2, 3, 4, 5} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) - res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) - fmt.Println(res3) //[]int{1, 2, 3, 4} + // Output: + // [a b c] + // [b c] + // [a b] + // [] } ``` @@ -449,18 +537,23 @@ func Every[T any](slice []T, predicate func(index int, item T) bool) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} - res := slice.Every(nums, isEven) - fmt.Println(res) //false + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Every(nums, isEven) + + fmt.Println(result) + + // Output: + // false } ``` @@ -478,20 +571,24 @@ func Equal[T comparable](slice1, slice2 []T) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{1, 2, 3} - slice3 := []int{3, 2, 1} + s1 := []int{1, 2, 3} + s2 := []int{1, 2, 3} + s3 := []int{1, 3, 2} - res1 := slice.Equal(slice1, slice2) - res2 := slice.Equal(slice1, slice3) + result1 := slice.Equal(s1, s2) + result2 := slice.Equal(s1, s3) - fmt.Println(res1) //true - fmt.Println(res2) //false + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // true + // false } ``` @@ -509,21 +606,24 @@ func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) boo ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{2, 4, 6} + s1 := []int{1, 2, 3} + s2 := []int{2, 4, 6} - isDouble := func(a, b int) bool { - return b == a*2 - } + isDouble := func(a, b int) bool { + return b == a*2 + } - res := slice.EqualWith(slice1, slice2, isDouble) + result := slice.EqualWith(s1, s2, isDouble) - fmt.Println(res) //true + fmt.Println(result) + + // Output: + // true } ``` @@ -541,18 +641,23 @@ func Filter[T any](slice []T, predicate func(index int, item T) bool) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res := slice.Filter(nums, isEven) - fmt.Println(res) //[]int{2, 4} + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Filter(nums, isEven) + + fmt.Println(result) + + // Output: + // [2 4] } ``` @@ -570,19 +675,25 @@ func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res, ok := slice.Find(nums, even) - fmt.Println(res) //2 - fmt.Println(ok) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result, ok := slice.Find(nums, isEven) + + fmt.Println(*result) + fmt.Println(ok) + + // Output: + // 2 + // true } ``` @@ -600,19 +711,25 @@ func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, boo ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 4, 5} - res, ok := slice.FindLast(nums, even) - fmt.Println(res) //4 - fmt.Println(ok) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result, ok := slice.FindLast(nums, isEven) + + fmt.Println(*result) + fmt.Println(ok) + + // Output: + // 4 + // true } ``` @@ -630,14 +747,19 @@ func Flatten(slice any) any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.Flatten(arr) - fmt.Println(res) //{{"a", "b"}, {"c", "d"}} + arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + + result := slice.Flatten(arrs) + + fmt.Println(result) + + // Output: + // [[a b] [c d]] } ``` @@ -655,14 +777,19 @@ func FlattenDeep(slice any) any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.FlattenDeep(arr) - fmt.Println(res) //[]string{"a", "b", "c", "d"} + arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + + result := slice.FlattenDeep(arrs) + + fmt.Println(result) + + // Output: + // [a b c d] } ``` @@ -680,17 +807,24 @@ func ForEach[T any](slice []T, iteratee func(index int, item T)) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 2, 3, 4, 5} - var numbersAddTwo []int - slice.ForEach(numbers, func(index int, value int) { - numbersAddTwo = append(numbersAddTwo, value+2) - }) - fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} + nums := []int{1, 2, 3} + + var result []int + addOne := func(_ int, v int) { + result = append(result, v+1) + } + + slice.ForEach(nums, addOne) + + fmt.Println(result) + + // Output: + // [2 3 4] } ``` @@ -708,19 +842,25 @@ func GroupBy[T any](slice []T, groupFn func(index int, item T) bool) ([]T, []T) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } - even, odd := slice.GroupBy(nums, evenFunc) + nums := []int{1, 2, 3, 4, 5} - fmt.Println(even) //[]int{2, 4, 6} - fmt.Println(odd) //]int{1, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } + + even, odd := slice.GroupBy(nums, isEven) + + fmt.Println(even) + fmt.Println(odd) + + // Output: + // [2 4] + // [1 3 5] } ``` @@ -738,21 +878,27 @@ func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []float64{6.1, 4.2, 6.3} - floor := func(num float64) float64 { - return math.Floor(num) - } - res := slice.GroupWith(nums, floor) - fmt.Println(res) //map[float64][]float64{ 4: {4.2}, 6: {6.1, 6.3},} + nums := []float64{6.1, 4.2, 6.3} + + floor := func(num float64) float64 { + return math.Floor(num) + } + + result := slice.GroupWith(nums, floor) //map[float64][]float64 + + fmt.Println(result) + + // Output: + // map[4:[4.2] 6:[6.1 6.3]] } ``` -### IntSlice (已弃用: 使用go1.18+泛型代替) +### IntSlice (已弃用: 使用 go1.18+泛型代替)将接口切片转换为int切片
@@ -766,18 +912,22 @@ func IntSlice(slice any) []int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var nums = []any{1, 2, 3} - res := slice.IntSlice(nums) - fmt.Println(res) //[]int{1, 2, 3} + nums := []interface{}{1, 2, 3} + + result := slice.IntSlice(nums) //[]int{1, 2, 3} + fmt.Println(result) + + // Output: + // [1 2 3] } ``` -### InterfaceSlice(已弃用: 使用go1.18+泛型代替) +### InterfaceSlice(已弃用: 使用 go1.18+泛型代替)将值转换为接口切片
@@ -791,14 +941,18 @@ func InterfaceSlice(slice any) []any ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var nums = []int{}{1, 2, 3} - res := slice.InterfaceSlice(nums) - fmt.Println(res) //[]any{1, 2, 3} + strs := []string{"a", "b", "c"} + + result := slice.InterfaceSlice(strs) //[]interface{}{"a", "b", "c"} + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -816,16 +970,20 @@ func Intersection[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 2, 3} - s2 := []int{1, 2, 3, 4} - res := slice.Intersection(s1, s2), + nums1 := []int{1, 2, 3} + nums2 := []int{2, 3, 4} - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Intersection(nums1, nums2) + + fmt.Println(result) + + // Output: + // [2 3] } ``` @@ -843,18 +1001,29 @@ func InsertAt[T any](slice []T, index int, value any) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s := []string{"a", "b", "c"} + result1 := slice.InsertAt([]string{"a", "b", "c"}, 0, "1") + result2 := slice.InsertAt([]string{"a", "b", "c"}, 1, "1") + result3 := slice.InsertAt([]string{"a", "b", "c"}, 2, "1") + result4 := slice.InsertAt([]string{"a", "b", "c"}, 3, "1") + result5 := slice.InsertAt([]string{"a", "b", "c"}, 0, []string{"1", "2", "3"}) - res1, _ := slice.InsertAt(s, 0, "1") - fmt.Println(res1) //[]string{"1", "a", "b", "c"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) - res2, _ := slice.InsertAt(s, 3, []string{"1", "2", "3"}) - fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} + // Output: + // [1 a b c] + // [a 1 b c] + // [a b 1 c] + // [a b c 1] + // [1 2 3 a b c] } ``` @@ -872,17 +1041,22 @@ func IndexOf[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.IndexOf(arr, "a") - fmt.Println(res1) //0 + strs := []string{"a", "a", "b", "c"} - res2 := slice.IndexOf(arr, "d") - fmt.Println(res2) //-1 + result1 := slice.IndexOf(strs, "a") + result2 := slice.IndexOf(strs, "d") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 0 + // -1 } ``` @@ -900,17 +1074,22 @@ func LastIndexOf[T comparable](slice []T, item T) int ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.LastIndexOf(arr, "a") - fmt.Println(res1) //1 + strs := []string{"a", "a", "b", "c"} - res2 := slice.LastIndexOf(arr, "d") - fmt.Println(res2) //-1 + result1 := slice.LastIndexOf(strs, "a") + result2 := slice.LastIndexOf(strs, "d") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1 + // -1 } ``` @@ -928,17 +1107,23 @@ func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - multiplyTwo := func(i, num int) int { - return num * 2 - } - res := slice.Map(nums, multiplyTwo) - fmt.Println(res) //[]int{2, 4, 6, 8} + nums := []int{1, 2, 3} + + addOne := func(_ int, v int) int { + return v + 1 + } + + result := slice.Map(nums, addOne) + + fmt.Println(result) + + // Output: + // [2 3 4] } ``` @@ -956,20 +1141,23 @@ func Merge[T any](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3} - s2 := []int{2, 4} - res := slice.Merge(s1, s2) + nums1 := []int{1, 2, 3} + nums2 := []int{3, 4} - fmt.Println(res) //[]int{1, 2, 3, 2, 4} + result := slice.Merge(nums1, nums2) + + fmt.Println(result) + + // Output: + // [1 2 3 3 4] } ``` - ### Reverse反转切片中的元素顺序
@@ -984,14 +1172,19 @@ func Reverse[T any](slice []T) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - slice.Reverse(nums) - fmt.Println(res) //[]int{4, 3, 2, 1} + strs := []string{"a", "b", "c", "d"} + + slice.Reverse(strs) + + fmt.Println(strs) + + // Output: + // [d c b a] } ``` @@ -1009,17 +1202,23 @@ func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initia ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4} - reduceFunc := func(i, v1, v2 int) int { - return v1 + v2 - } - res := slice.Reduce(nums, reduceFunc, 0) - fmt.Println(res) //10 + nums := []int{1, 2, 3} + + sum := func(_ int, v1, v2 int) int { + return v1 + v2 + } + + result := slice.Reduce(nums, sum, 0) + + fmt.Println(result) + + // Output: + // 6 } ``` @@ -1037,18 +1236,31 @@ func Replace[T comparable](slice []T, old T, new T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b", "a", "c", "d", "a"} + strs := []string{"a", "b", "c", "a"} - fmt.Println(slice.Replace(strs, "a", "x", 0)) //{"a", "b", "a", "c", "d", "a"} + result1 := slice.Replace(strs, "a", "x", 0) + result2 := slice.Replace(strs, "a", "x", 1) + result3 := slice.Replace(strs, "a", "x", 2) + result4 := slice.Replace(strs, "a", "x", 3) + result5 := slice.Replace(strs, "a", "x", -1) - fmt.Println(slice.Replace(strs, "a", "x", 1)) //{"x", "b", "a", "c", "d", "a"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) - fmt.Println(slice.Replace(strs, "a", "x", -1)) //{"x", "b", "x", "c", "d", "x"} + // Output: + // [a b c a] + // [x b c a] + // [x b c x] + // [x b c x] + // [x b c x] } ``` @@ -1066,16 +1278,17 @@ func ReplaceAll[T comparable](slice []T, old T, new T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - strs := []string{"a", "b", "a", "c", "d", "a"} + result := slice.ReplaceAll([]string{"a", "b", "c", "a"}, "a", "x") - fmt.Println(slice.ReplaceAll(strs, "a", "x")) //{"x", "b", "x", "c", "d", "x"} + fmt.Println(result) - fmt.Println(slice.Replace(strs, "e", "x")) //{"a", "b", "a", "c", "d", "a"} + // Output: + // [x b c x] } ``` @@ -1093,16 +1306,20 @@ func Repeat[T any](item T, n int) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - fmt.Println(slice.Repeat("a", 3)) //[]string{"a", "a", "a"} + result := slice.Repeat("a", 3) + + fmt.Println(result) + + // Output: + // [a a a] } ``` - ### Shuffle随机打乱切片中的元素顺序
@@ -1117,14 +1334,18 @@ func Shuffle[T any](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5} - res := slice.Shuffle(nums) - fmt.Println(res) //3,1,5,4,2 + nums := []int{1, 2, 3, 4, 5} + result := slice.Shuffle(nums) + + fmt.Println(res) + + // Output: + // [3 1 5 4 2] (random order) } ``` @@ -1142,30 +1363,29 @@ func Sort[T constraints.Ordered](slice []T, sortOrder ...string) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 4, 3, 2, 5} - - slice.Sort(numbers) - fmt.Println(numbers) //{1,2,3,4,5} + numbers := []int{1, 4, 3, 2, 5} - slice.Sort(numbers, "desc") - fmt.Println(numbers) //{5,4,3,2,1} + slice.Sort(numbers) + fmt.Println(numbers) // [1 2 3 4 5] - strings := []string{"a", "d", "c", "b", "e"} + slice.Sort(numbers, "desc") + fmt.Println(numbers) // [5 4 3 2 1] - slice.Sort(strings) - fmt.Println(strings) //{"a", "b", "c", "d", "e"} + strings := []string{"a", "d", "c", "b", "e"} - slice.Sort(strings, "desc") - fmt.Println(strings) //{"e", "d", "c", "b", "a"} + slice.Sort(strings) + fmt.Println(strings) //[a b c d e} + + slice.Sort(strings, "desc") + fmt.Println(strings) //[e d c b a] } ``` - ### SortBy按照less函数确定的升序规则对切片进行排序。排序不保证稳定性
@@ -1180,41 +1400,40 @@ func SortBy[T any](slice []T, less func(a, b T) bool) ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - numbers := []int{1, 4, 3, 2, 5} + numbers := []int{1, 4, 3, 2, 5} - slice.SortBy(numbers, func(a, b int) bool { - return a < b - }) - fmt.Println(numbers) //{1, 2, 3, 4, 5} + slice.SortBy(numbers, func(a, b int) bool { + return a < b + }) + fmt.Println(numbers) // [1 2 3 4 5] - type User struct { - Name string - Age uint - } + type User struct { + Name string + Age uint + } - users := []User{ - {Name: "a", Age: 21}, - {Name: "b", Age: 15}, - {Name: "c", Age: 100}} + users := []User{ + {Name: "a", Age: 21}, + {Name: "b", Age: 15}, + {Name: "c", Age: 100}} - slice.SortBy(users, func(a, b User) bool { - return a.Age < b.Age - }) + slice.SortBy(users, func(a, b User) bool { + return a.Age < b.Age + }) - fmt.Printf("sort users by age: %v", users) + fmt.Printf("sort users by age: %v", users) - // output - // [{b 15} {a 21} {c 100}] + // output + // [{b 15} {a 21} {c 100}] } ``` - -### SortByField (已弃用: 请使用 Sort或SortBy 代替该方法) +### SortByField (已弃用: 请使用 Sort 或 SortBy 代替该方法)按字段对结构切片进行排序。slice元素应为struct,字段类型应为int、uint、string或bool。 默认排序类型是升序(asc),如果是降序,设置 sortType 为 desc
@@ -1228,32 +1447,30 @@ func SortByField(slice any, field string, sortType ...string) error ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - type student struct { - name string - age int - } - students := []student{ - {"a", 10}, - {"b", 15}, - {"c", 5}, - {"d", 6}, - } - err := slice.SortByField(students, "age", "desc") - if err != nil { - fmt.Println(err) - } - fmt.Println(students) - // []students{ - // {"b", 15}, - // {"a", 10}, - // {"d", 6}, - // {"c", 5}, - // } + type User struct { + Name string + Age uint + } + + users := []User{ + {Name: "a", Age: 21}, + {Name: "b", Age: 15}, + {Name: "c", Age: 100}} + + err := slice.SortByField(users, "Age", "desc") + if err != nil { + return + } + + fmt.Println(users) + + // Output: + // [{c 100} {a 21} {b 15}] } ``` @@ -1271,22 +1488,27 @@ func Some[T any](slice []T, predicate func(index int, item T) bool) bool ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} - res := slice.Some(nums, isEven) - fmt.Println(res) //true + isEven := func(i, num int) bool { + return num%2 == 0 + } + + result := slice.Some(nums, isEven) + + fmt.Println(result) + + // Output: + // true } ``` -### StringSlice(已弃用: 使用go1.18+泛型代替) +### StringSlice(已弃用: 使用 go1.18+泛型代替)将接口切片转换为字符串切片
@@ -1300,14 +1522,18 @@ func StringSlice(slice any) []string ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - var s = []any{"a", "b", "c"} - res := slice.StringSlice(s) - fmt.Println(res) //[]string{"a", "b", "c"} + strs := []interface{}{"a", "b", "c"} + + result := slice.StringSlice(strs) //[]string{"a", "b", "c"} + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -1325,18 +1551,20 @@ func SymmetricDifference[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 2, 3} - s2 := []int{1, 2, 4} - s3 := []int{1, 2, 3, 5} + nums1 := []int{1, 2, 3} + nums2 := []int{1, 2, 4} - fmt.Println(slice.SymmetricDifference(s1)) //[]int{1, 2, 3} - fmt.Println(slice.SymmetricDifference(s1, s2)) //[]int{3, 4} - fmt.Println(slice.SymmetricDifference(s1, s2, s3)) //[]int{3, 4, 5} + result := slice.SymmetricDifference(nums1, nums2) + + fmt.Println(result) + + // Output: + // [3 4] } ``` @@ -1354,13 +1582,17 @@ func ToSlice[T any](items ...T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.ToSlice("a", "b") - fmt.Println(res) //{"a", "b"} + result := slice.ToSlice("a", "b", "c") + + fmt.Println(result) + + // Output: + // [a b c] } ``` @@ -1378,15 +1610,24 @@ func ToSlicePointer[T any](items ...T) []*T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - str1 := "a" - str2 := "b" - res := slice.ToSlicePointer(str1, str2) - fmt.Println(res) // res -> []*string{&str1, &str2} + str1 := "a" + str2 := "b" + + result := slice.ToSlicePointer(str1, str2) + + expect := []*string{&str1, &str2} + + isEqual := reflect.DeepEqual(result, expect) + + fmt.Println(isEqual) + + // Output: + // true } ``` @@ -1404,13 +1645,16 @@ func Unique[T comparable](slice []T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Unique([]int{1, 2, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + result := slice.Unique([]string{"a", "a", "b"}) + fmt.Println(result) + + // Output: + // [a b] } ``` @@ -1428,15 +1672,20 @@ func UniqueBy[T comparable](slice []T, iteratee func(item T) T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { - return val % 4 - }) - fmt.Println(res) //[]int{1, 2, 3, 0} + nums := []int{1, 2, 3, 4, 5, 6} + result := slice.UniqueBy(nums, func(val int) int { + return val % 3 + }) + + fmt.Println(result) + + // Output: + // [1 2 0] } ``` @@ -1454,16 +1703,20 @@ func Union[T comparable](slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s1 := []int{1, 3, 4, 6} - s2 := []int{1, 2, 5, 6} - res := slice.Union(s1, s2) + nums1 := []int{1, 3, 4, 6} + nums2 := []int{1, 2, 5, 6} - fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} + result := slice.Union(nums1, nums2) + + fmt.Println(result) + + // Output: + // [1 3 4 6 2 5] } ``` @@ -1481,16 +1734,22 @@ func UnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - testFunc := func(i int) int { - return i / 2 - } - result := slice.UnionBy(testFunc, []int{0, 1, 2, 3, 4, 5}, []int{0, 2, 10}) - fmt.Println(result) //[]int{0, 2, 4, 10} + nums := []int{1, 2, 3, 4} + + divideTwo := func(n int) int { + return n / 2 + } + result := slice.UnionBy(divideTwo, nums) + + fmt.Println(result) + + // Output: + // [1 2 4] } ``` @@ -1508,15 +1767,29 @@ func UpdateAt[T any](slice []T, index int, value T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - s := []string{"a", "b", "c"} + result1 := slice.UpdateAt([]string{"a", "b", "c"}, -1, "1") + result2 := slice.UpdateAt([]string{"a", "b", "c"}, 0, "1") + result3 := slice.UpdateAt([]string{"a", "b", "c"}, 1, "1") + result4 := slice.UpdateAt([]string{"a", "b", "c"}, 2, "1") + result5 := slice.UpdateAt([]string{"a", "b", "c"}, 3, "1") - res1, _ := slice.UpdateAt(s, 0, "1") - fmt.Println(res1) //[]string{"1", "b", "c"} + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + fmt.Println(result5) + + // Output: + // [a b c] + // [1 b c] + // [a 1 c] + // [a b 1] + // [a b c] } ``` @@ -1534,17 +1807,20 @@ func Without[T comparable](slice []T, items ...T) []T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) - fmt.Println(res) //[]int{3, 4, 5} + result := slice.Without([]int{1, 2, 3, 4}, 1, 2) + + fmt.Println(result) + + // Output: + // [3 4] } ``` - ### KeyBy将切片每个元素调用函数后转为map
@@ -1559,15 +1835,18 @@ func KeyBy[T any, U comparable](slice []T, iteratee func(item T) U) map[U]T ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.KeyBy([]string{"a", "ab", "abc"}, func(str string) int { - return len(str) - }) + result := slice.KeyBy([]string{"a", "ab", "abc"}, func(str string) int { + return len(str) + }) - fmt.Println(res) //map[int]string{1: "a", 2: "ab", 3: "abc"} + fmt.Println(result) + + // Output: + // map[1:a 2:ab 3:abc] } ``` diff --git a/random/random_example_test.go b/random/random_example_test.go index 42ae146..9c51d66 100644 --- a/random/random_example_test.go +++ b/random/random_example_test.go @@ -6,7 +6,6 @@ import ( ) func ExampleRandInt() { - result := RandInt(1, 10) if result >= 1 && result < 10 {