`package main
import (
"crypto/md5"
"fmt"
"log"
"math"
"math/bits"
"math/rand"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"te"
"time"
"unsafe"
//"hash"
"encoding/hex"
fstate "fsm"
"io"
"regexp"
"text/tabwriter"
"path/filepath"
"errors"
"context"
)
var c bool
var age int
var score float32
var tree, tree2 uint16
var list []uint
func main() {
// _, txt := addStr(1, "new")
// fmt.Println("Google" + "Runoob", txt)
// var man male
// fu := man.change(6,5)
// fmt.Println("===>>", fu())
//main1()
//te.When()
rand.Seed(time.Now().Unix())
randseed = time.Now().UnixNano()
mainfi()
}
const (
Unknown = "1123swerwe"
Female = len(Unknown)
Male = unsafe.Sizeof(Unknown)
Today = iota
Nice
)
func addStr(num int, str string) (a, b int) {
age = 1
newd := 1
body, newd := age, 1
age += body
arr := []int{1, 23, 34, 3, 63}
slice1 := make([]int, 5)
fmt.Println(Unknown, Female, Male, unsafe.Sizeof(arr), Today, Nice)
bload(arr)
for k, v := range slice1 {
fmt.Println(k, v)
}
const Length int = 1
return age, newd
}
func bload(arr []int) {
arr[len(arr)-1] = 999
}
type male struct {
body float32
}
func (c male) change(a, b int) func() int {
NCC:
if a >= b {
fmt.Println(a, "big")
a = a - 1
goto NCC
} else {
fmt.Println(a, "small")
}
return func() int {
a++
return a
}
}
// 定义一个 DivideError 结构
type DivideError struct {
dividee int
divider int
}
func (obj *DivideError) Div() {
obj.dividee = 10
obj.divider = 9
}
func (obj DivideError) Div1() {
obj.dividee = 100
obj.divider = 90
}
// 实现 error
接口
func (de *DivideError) Error() string {
strFormat := Cannot proceed, the divider is zero. dividee: %d divider: 0
return fmt.Sprintf(strFormat, de.dividee)
}
// 定义 int
类型除法运算的函数
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
if varDivider == 0 {
dData := DivideError{
dividee: varDividee,
divider: varDivider,
}
errorMsg = dData.Error()
return
} else {
return varDividee / varDivider, ""
}
}
func main1() {
if result, errorMsg := Divide(100, 10); errorMsg == "" {
fmt.Println("100/10 = ", result)
}
// 当除数为零的时候会返回错误信息
if _, errorMsg := Divide(100, 0); errorMsg != "" {
fmt.Println("errorMsg is: ", errorMsg)
}
chans()
maps()
var di DivideError
di.Div()
//fmt.Println("====>>>>", di.dividee, di.divider)
}
func worker(id int, c chan int) {
for {
fmt.Printf("worker %d run %c
", id, <-c)
}
}
func chans() {
// var channels [10]chan int
// for i:=0;i<2;i++{
// channels[i]=make(chan int)
// go worker(i,channels[i])
// }
// for i:=0;i<10;i++{
// channels[0] <- 'a'+i
// }
// fmt.Println("=======>>>")
// for i:=0;i<10;i++{
// channels[1] <- 'A'+i
// }
}
func maps() {
var contryMap map[string]string = make(map[string]string)
contryMap["nis"] = "nik"
contryMap["nid"] = "nikw"
contryMap["ni"] = "nikd"
for k, v := range contryMap {
fmt.Println(k, v)
}
fmt.Println("dd", contryMap["ni"+"s"])
fun(callback).call(2)
mains()
}
func mains() {
fmt.Printf(">>>>%T
", 123)
type cat struct {
Name string
Type int `json:"type" id:"100"`
}
typeOfCat := reflect.TypeOf(cat{})
if catType, ok := typeOfCat.FieldByName("Type"); ok {
fmt.Println(catType.Tag.Get("json"))
fmt.Println(catType.Tag.Get("id"))
}
//main2()
main3()
}
//需要传递函数
func callback(i int) {
d := &i
fmt.Println("i am callBack", reflect.TypeOf(d))
fmt.Println(i)
}
//定义的type函数
type fun func(int)
//fun实现的Call接口的call()函数
func (f fun) call(i int) {
f(i)
}
//接口
// type Call interface {
// call(int)
// }
// 崩溃时需要传递的上下文信息
type panicContext struct {
functionss string // 所在函数
function int // 所在函数
}
// 保护方式允许一个函数
func ProtectRun(entry func()) {
//延迟处理的函数
defer func() {
// 发生宕机时,获取panic传递的上下文并打印
err := recover()
switch err.(type) {
case runtime.Error: // 运行时错误
fmt.Println("runtime error:", err)
default: // 非运行时错误
fmt.Println("error:", err)
}
}()
entry()
}
func main2() {
fmt.Println("运行前")
// 允许一段手动触发的错误
ProtectRun(func() {
fmt.Println("手动宕机前")
// 使用panic传递上下文
panic(&panicContext{
"手动触发panic",
555,
})
fmt.Println("手动宕机后")
})
// 故意造成空指针访问错误
ProtectRun(func() {
fmt.Println("赋值宕机前")
var a *int
*a = 1
fmt.Println("赋值宕机后")
})
fmt.Println("运行后")
}
type coder interface {
code()
debug()
}
type Gopher struct {
num int
language string
}
func (p Gopher) code() {
p.num++
fmt.Printf("I am coding %s language, num is %d
", p.language, p.num)
}
func (p *Gopher) debug() {
p.num++
fmt.Printf("I am debuging %s language, num is %d
", p.language, p.num)
}
func maintest() {
// var take coder
// take = &Gopher{100, "doing"}
// take.code()
// take.debug()
// take.code()
lsInt := make(chan int)
fmt.Println("6666666", time.Second)
count := 0
var lock sync.Mutex
go func() {
for i := 0; i < 26; i++ {
lock.Lock()
count = count + 1
fmt.Println("go<<<", i, count)
lock.Unlock()
lsInt <- i
}
}()
go func() {
for i := 0; i < 16; i++ {
m := <-lsInt
lock.Lock()
count = count + 1
fmt.Println("go>>>", m, count)
lock.Unlock()
}
}()
m := <-lsInt
lock.Lock()
count = count + 1
fmt.Println("main>>>", m, count)
lock.Unlock()
fmt.Println("zzzzz", count)
}
func mainos() {
// 预定义变量, 保存命令行参数
fmt.Println(os.Args)
// 获取host name
fmt.Println(os.Hostname())
fmt.Println(os.Getpid())
// 获取全部环境变量
// env := os.Environ()
// for k, v := range env {
// fmt.Println(k, v)
// }
// 终止程序
// os.Exit(1)
// 获取一条环境变量
//fmt.Println(os.Getenv("PATH"))
// 获取当前目录
dir, err := os.Getwd()
fmt.Println(dir, err)
// 创建目录
err = os.Mkdir(dir+"/new_file", 0755)
fmt.Println(err)
// 创建目录
err = os.MkdirAll(dir+"/new", 0755)
fmt.Println(err)
// 删除目录
err = os.Remove(dir + "/new_file")
err = os.Remove(dir + "/new")
fmt.Println(err)
// 创建临时目录
tmp_dir := os.TempDir()
fmt.Println(tmp_dir)
}
func findRoad(r *int) {
log.Println("road:", *r)
}
func entry() {
rd := int(999)
r := &rd
runtime.SetFinalizer(r, findRoad)
}
func main3() {
// entry()
// for i := 0; i < 3; i++ {
// time.Sleep(time.Second)
// runtime.GC()
// }
var x float64 = 3.4
//data := reflect.TypeOf(x)
value := reflect.ValueOf(x)
// floatData := value.Float()
// floatData = 1.3
over := value.Interface()
fmt.Println(reflect.TypeOf(over), reflect.TypeOf(over.(float64)), over, interface{}(interface{}(over)).(float64), interface{}(x).(float64))
return
}
func KeyPrefix(str interface{}) (prefix string) {
t := reflect.TypeOf(str).Elem()
prefix = fmt.Sprintf("%s_%s_", "india_game", t.String())
return
}
type pick struct {
str string
co int
}
type Person05 struct {
name string
sex string
age int
}
func (p Person05) printInfo() {
fmt.Printf("55>>名称:%s, 性别:%s, 年龄:%d
", p.name, p.sex, p.age)
}
type inter interface {
printInfo()
}
type Person04 struct {
Person05
sex bool
name string
age int
}
func (p Person04) printInfo() {
fmt.Printf("44>>名称:%s, 性别:%s, 年龄:%d
", p.name, p.sex, p.age)
}
type Student struct {
Person05
id int
}
func Float64bits(f float64) uint64 { return (uint64)(unsafe.Pointer(&f)) }
//func Float64bits(f, m float64){ return (uint64)(unsafe.Pointer(&f)) }
func init() {
}
func init() {
}
func main61() {
// str := "zzzzzz"
// m := KeyPrefix(&str)
// fmt.Println(m)
// picks := pick{}
// fmt.Println(&picks, &picks.co,&(picks.co), (&picks).co)
// user := pick{"go", 3}
// fmt.Printf("%v %v
", user, &user)
// fmt.Printf("%+v %+v
", user, &user)
// fmt.Printf("%#v %#v
", user, &user)
// done := make(chan int, 1) // 带缓存通道
// go func() {
// fmt.Println(">>>>>1")
// <-done
// fmt.Println(">>>>>2")
// }()
// fmt.Println(">>>>>3")
// done <- 1
// fic.When(2)
// //fic2.When(3)
//fic.When(2)
// //fic2.When(3)
// fic2.Put()
// oldList := []int {1,2,3,4,5,6}
// i := 3
// fmt.Println(oldList[:1], oldList[i+1:])
// oldList = append(oldList[:i], oldList[i+1:]...)
// fmt.Println(oldList)
// x := []int {1,2,3}
// //注意下面这两个区别
// fmt.Println(append(x,4,5,6), x)
// if(fic.When == nil){
// fmt.Println("kkkkkkkk")
// }
// u := uint32(32)
// i := int32(1)
// fmt.Println(&u, &i)
// p := &i
// fmt.Println(">>",unsafe.Pointer(&u))
// p = (*int32)(unsafe.Pointer(&u))
// fmt.Println(*p)
// flo := 3.5
// fmt.Println(Float64bits(flo))
p := Person04{Person05{}, true, "putty", 10}
fmt.Println(p)
fmt.Println("SIZE", &(p), &(p.sex), &(p.name), &(p.age))
lang := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) + 24))
*lang = 20
fmt.Println(p)
// var x struct {
// a bool
// b string
// c bool
// b1 bool
// c1 bool
// d int32
// e []int
// }
// fmt.Println("SIZE", &(x),&(x.a),&(x.b),&(x.c),&(x.b1),&(x.c1),&(x.d),&(x.e))
// //Alignof 返回 m,m 是指当类型进行内存对齐时,它分配到的内存地址能整除 m。
// //fmt.Println("ALIGN",unsafe.Alignof(x),unsafe.Alignof(x.a),unsafe.Alignof(x.b),unsafe.Alignof(x.c))
// fmt.Println("OFFSET",0, unsafe.Offsetof(x.a), unsafe.Offsetof(x.b), unsafe.Offsetof(x.c))
// recover()
// a := make([]func(), 3 )
// i := 0
// for ; i < 3; i++ {
// a[i]= func( ){
// fmt.Println(i)
// }
// }
// defer func(){ fmt.Println("Zzz")}()
// defer func(){ }()
// defer func(){ fmt.Println("Zzz2")}()
// panic("zjjj")
//i = 6
// for _, s := range a {
// s()
// }
}
func main66() {
// defer func() {
// fmt.Println(recover())
// fmt.Printf(">>>%T", recover())
// }()
// fmt.Println(1, nil)
// a := []int{123}
// a[0] = 2
// maps := map[string]interface{}{}
// maps["student4"] = Person04
// maps["student5"] = student5
// fmt.Println("struct to string")
num := Person04{Person05{}, true, "putty", 10}
// if abs, ok := interface{}(num.name).(string); ok {
// fmt.Println("zzzzz", abs)
// }
num.printInfo()
v2 := reflect.ValueOf(num)
fmt.Println(">>", v2.Type())
// go func() {
// for {
// fmt.Println("goroutine1_print")
// }
// }()
// // 协程B
// go func() {
// time.Sleep(1 * time.Second)
// panic("goroutine2_panic")
// }()
// time.Sleep(20 * time.Second)
str := "LUCKY SPIN is wai@ting for YOU! Our players has won more than 1 Lakh totally in LUCKY SPIN today!Your city's player has won 2 Lakh in Poker today, come to WIN BIGGER!"
GetRandomStr(str)
// for i := 1; i< 80; i++ {
// fmt.Println(RandInt(3))
// }
x := 11
y := (1 << 0) | (1 << 3) //保证 z 中的第 0 位和第 3 位为 0
z := x &^ y
fmt.Printf("x = %b
", x)
fmt.Println(" &^")
fmt.Printf("y = %b
", y)
fmt.Println("————————")
fmt.Printf("z = %04b
", z)
}
func RandInt(max int) int {
if max <= 1 {
return 1
}
rr := rand.New(rand.NewSource(time.Now().UnixNano() * rand.Int63n(9999)))
return rr.Intn(max) + 1
}
//分隔符@
func GetRandomStr(str string) {
strLs := strings.Split(str, "@")
for k, str := range strLs {
fmt.Println(k, str)
}
fmt.Println(strLs[RandInt(len(strLs))-1])
}
const m0 = 0x5555555555555555 // 01010101 ...
const m1 = 0x3333333333333333 // 00110011 ...
const m2 = 0x0f0f0f0f0f0f0f0f // 00001111 ...
const m3 = 0x00ff00ff00ff00ff // etc.
const m4 = 0x0000ffff0000ffff
func P64(x uint64) {
str := ""
for i := 0; i < 64; i++ {
str = fmt.Sprint(x>>i&1, str)
}
fmt.Println(x, ">>>", str)
}
func P32(x uint64) {
str := ""
for i := 0; i < 32; i++ {
str = fmt.Sprint(x>>i&1, str)
}
fmt.Println(x, ">>>", str)
}
func P16(x uint64) {
str := ""
for i := 0; i < 16; i++ {
str = fmt.Sprint(x>>i&1, str)
}
fmt.Println(x, ">>>", str)
}
func onecnt(x uint64) int {
count := 0
for ; x > 0; x = x & (x - 1) {
count++
}
return count
}
func onetest(x uint64) {
const m = 1<<64 - 1
fmt.Println(x, x&m)
//var s te.StateStr
}
// func (x *StateStr)take() {
// }
func OnesCount64(x uint64) int {
const m = 1<<64 - 1
x = x>>1&(m0&m) + x&(m0&m)
x = x>>2&(m1&m) + x&(m1&m)
x = (x>>4 + x) & (m2 & m)
x += x >> 8
x += x >> 16
x += x >> 32
fmt.Println("==>", m0&m)
return int(x) & (1<<7 - 1)
}
func Abs(n float64) float64 {
return float64bits(bittofloat(n) &^ (1 << 63))
}
func float64bits(n uint64) float64 {
return (float64)(unsafe.Pointer(&n))
}
func bittofloat(n float64) uint64 {
return (uint64)(unsafe.Pointer(&n))
}
func GetFunctionName(i interface{}, seps ...rune) string {
// 获取函数名称
fmt.Println("**>>>>", runtime.FuncForPC(reflect.ValueOf(i).Pointer()))
fn := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
// 用 seps 进行分割
fields := strings.FieldsFunc(fn, func(sep rune) bool {
for _, s := range seps {
if sep == s {
return true
}
}
return false
})
fmt.Println(fields)
if size := len(fields); size > 0 {
return fields[size-1]
}
return ""
}
func Println(v uint64) {
P16(v)
}
func getlog(v uint32) uint32 {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
v = tab32[(v*0x077CB531)>>27]
return v
}
const digits = "0123456789abcdefghijklmnopqrstuvwxyz"
var tab32 = [32]uint32{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}
func main106() {
uintSize := 32 << (^int64(0) >> 32 & 1)
b := 1e20
fmt.Println(^uint(0), ^uint(0)>>32, (^uint(0) >> 32 & 1), uintSize)
const m = 1<<64 - 1
fmt.Println(b, m>>1&(^int64(0)), OnesCount64(4095), onecnt(4096))
onetest(409)
P16(123)
P16(123 &^ 6)
fmt.Println("name:", GetFunctionName(P16))
// P64(bittofloat(-0.1251234))
// P64(bittofloat(-1))
var pi te.StateStr
pi.Fill()
curT := time.Now()
const sun = iota
fmt.Println(">>>", curT.Nanosecond(), sun, time.Now().UTC())
// const char g_math_32[] ={0,1,23,2,29,24,14,3,30,27,25,18,20,15,10,4,31,22,28,13,26,17,19,9,21,12,16,8,11,7,6,5};
// #define LOG2(v) g_math_32[(uint32_t)((v) * 0x7dcd629) >> 27]
fmt.Println(strconv.FormatInt(127, 2))
var un uint64 = 88
un = -un
string_number := 869702343
result := fmt.Sprint(string_number)
fmt.Println(result)
x := 0x077CB531
fmt.Println((x & -x))
fmt.Printf("%T
", result)
fmt.Println("===", digits[1:2], un, bits.TrailingZeros(2), getlog(120), bits.LeadingZeros(1<<60+4641213))
slice := make([]byte, 0)
slice1 := strconv.AppendBool(slice, false) // []byte中添加bool类型 (bool-->[]byte)
fmt.Println(string(slice1)) // false
slice2 := strconv.AppendInt(slice, 123, 2) // 2:二进制
fmt.Println(string(slice2)) // 1111011
slice3 := strconv.AppendFloat(slice, 3.141592, 'f', 4, 64) // 4:保留4位。 64:float64
fmt.Println(string(slice3)) // 3.1416
slice4 := strconv.AppendQuote(slice, "hello")
fmt.Println(string(slice4), reflect.ValueOf(slice3).Len()) // "hello" (包含双引号)
for k, v := range slice {
fmt.Println(k, v)
}
}
func requiresQuotes(u string) bool {
// When type URL contains any characters except [0-9A-Za-z./-]*, it must be quoted.
for , ch := range u {
switch {
case ch == '.' || ch == '/' || ch == '':
continue
case '0' <= ch && ch <= '9':
continue
case 'A' <= ch && ch <= 'Z':
continue
case 'a' <= ch && ch <= 'z':
continue
default:
return true
}
}
return false
}
func RandIntervalN(b1, b2 int32, n uint32) []int32 {
if b1 == b2 {
return []int32{b1}
}
min, max := int64(b1), int64(b2)
if min > max {
min, max = max, min
}
l := max - min + 1
if int64(n) > l {
n = uint32(l)
}
r := make([]int32, n)
m := make(map[int32]int32)
for i := uint32(0); i < n; i++ {
v := int32(rand.Int63n(l) + min)
//v := int32(Getrand(min, max))
if mv, ok := m[v]; ok {
r[i] = mv
} else {
r[i] = v
}
lv := int32(l - 1 + min)
if v != lv {
if mv, ok := m[lv]; ok {
m[v] = mv
} else {
m[v] = lv
}
}
l--
}
return r
}
func RandGroup(p ...uint32) int {
if p == nil {
panic("args not found")
}
r := make([]uint32, len(p))
for i := 0; i < len(p); i++ {
if i == 0 {
r[0] = p[0]
} else {
r[i] = r[i-1] + p[i]
}
}
rl := r[len(r)-1]
if rl == 0 {
return 0
}
rn := uint32(rand.Int63n(int64(rl)))
for i := 0; i < len(r); i++ {
if rn < r[i] {
return i
}
}
panic("bug")
}
func deepCopy(dst, src reflect.Value) {
switch src.Kind() {
case reflect.Interface:
value := src.Elem()
if !value.IsValid() {
return
}
newValue := reflect.New(value.Type()).Elem()
deepCopy(newValue, value)
dst.Set(newValue)
case reflect.Ptr:
value := src.Elem()
if !value.IsValid() {
return
}
dst.Set(reflect.New(value.Type()))
deepCopy(dst.Elem(), value)
case reflect.Map:
dst.Set(reflect.MakeMap(src.Type()))
keys := src.MapKeys()
for _, key := range keys {
value := src.MapIndex(key)
newValue := reflect.New(value.Type()).Elem()
deepCopy(newValue, value)
dst.SetMapIndex(key, newValue)
}
case reflect.Slice:
dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap()))
for i := 0; i < src.Len(); i++ {
deepCopy(dst.Index(i), src.Index(i))
}
case reflect.Struct:
typeSrc := src.Type()
for i := 0; i < src.NumField(); i++ {
value := src.Field(i)
tag := typeSrc.Field(i).Tag
if value.CanSet() && tag.Get("deepcopy") != "-" {
deepCopy(dst.Field(i), value)
}
}
default:
dst.Set(src)
}
}
func DeepCopy(dst, src interface{}) {
typeDst := reflect.TypeOf(dst)
typeSrc := reflect.TypeOf(src)
if typeDst != typeSrc {
panic("DeepCopy: " + typeDst.String() + " != " + typeSrc.String())
}
if typeSrc.Kind() != reflect.Ptr {
panic("DeepCopy: pass arguments by address")
}
valueDst := reflect.ValueOf(dst).Elem()
valueSrc := reflect.ValueOf(src).Elem()
if !valueDst.IsValid() || !valueSrc.IsValid() {
panic("DeepCopy: invalid arguments")
}
deepCopy(valueDst, valueSrc)
}
func DeepClone(v interface{}) interface{} {
dst := reflect.New(reflect.TypeOf(v)).Elem()
deepCopy(dst, reflect.ValueOf(v))
return dst.Interface()
}
func Perm(n int) []int {
m := make([]int, n)
for i := 0; i < n; i++ {
j := rand.Intn(i + 1)
m[i] = m[j]
m[j] = i
fmt.Println(i, m[i], ">>", j, m[j])
}
return m
}
func C(sum, lec int) int {
ret := 1
low := 1
for i := 0; i < lec; i++ {
ret *= sum - i
low *= lec - i
}
// str := fmt.Sprint("C(", sum , ",", lec ,")" , ret/low)
// fmt.Println(str)
return ret / low
}
func Clist(para ...int) int {
all := 1
for i := 0; i < len(para); i += 2 {
all *= C(para[i], para[i+1])
}
return all
}
func Csum(para ...[]int) int {
all := 0
for i := 0; i < len(para); i++ {
all += Clist(para[i]...)
}
return all
}
var randseed int64 = 456213
func Getrand(min, max int64) int64 {
randseed = randseed >> 32 << 32
randseed := (1103515245*randseed + 1) % (2<<31 - 1)
fmt.Println(randseed)
if randseed < 0 {
randseed = -randseed
}
return randseed%(max-min+1) + min
}
func checkflo(flo map[int]int) bool {
for k := range flo {
if flo[k+1] > 0 && flo[k+2] > 0 && flo[k+3] > 0 && flo[k+4] > 0 {
return true
}
}
return false
}
func countdz() {
cards := make([]int, 0)
for i := 1; i < 14; i++ {
cards = append(cards, i)
cards = append(cards, i)
cards = append(cards, i)
cards = append(cards, i)
}
allcount := 1000000
count := make(map[string]int)
flocount := 0
for allcount > 0 {
allcount--
rand.Seed(int64(allcount))
selects := RandIntervalN(0, 51, 7)
static := make(map[int]int)
for i := 0; i < len(selects); i++ {
if v, ok := static[cards[selects[i]]]; ok {
static[cards[selects[i]]] = v + 1
} else {
static[cards[selects[i]]] = 1
}
}
if checkflo(static) {
flocount++
}
chipList := make([]int, 0)
for _, v := range static {
chipList = append(chipList, v)
}
sort.Ints(chipList)
arrStr := ""
for i := 0; i < len(chipList); i++ {
arrStr += strconv.Itoa(chipList[i])
}
if _, ok := count[arrStr]; ok {
count[arrStr]++
} else {
count[arrStr] = 1
}
}
fmt.Println(">>", count, flocount)
}
type special int32
func main6f() {
// strconv.ParseInt(...) fastest
// strconv.Atoi(...) still very fast
// fmt.Sscanf(...) not terribly fast but most flexible
// pstr := new(Person05)
// pstr.printInfo()
num := -1 << 63
num = num | (1<<63 - 1)
//newnum := (uint64)(unsafe.Pointer(&num))
//P64(newnum)
if requiresQuotes("sadfa32423") {
fmt.Println(">>>>#$%^&(")
}
nums := 3
find:
for {
switch {
case nums > 1:
fmt.Println("gjk")
nums--
case 2 > 1:
fmt.Println("999")
break find
}
}
// int32list := RandIntervalN(1, 10, 10)
// fmt.Println(int32list)
// fmt.Println(RandGroup(1,0,3))
// fmt.Println(Perm(10))
// fmt.Println(1<<0)
// v := Person04{}
// dst := reflect.New(reflect.TypeOf(v)).Elem()
// var picks special = 3
// var picks2 special = 2
// mk := picks + picks2
// fmt.Println(v, dst, mk)
//133784560
for i := 0; i < 100; i++ {
fmt.Println(Getrand(1, 10))
}
C(13, 7)
C(12, 5)
var arr [][]int = [][]int{
{52, 7},
{13, 7}, //1
{13, 1, 12, 5}, {13, 2, 11, 3}, {13, 3, 10, 1},
{13, 1, 12, 4}, {13, 2, 11, 1},
{13, 1, 12, 3},
{13, 2, 2, 1, 11, 2}, //3+2
{13, 2, 2, 1, 11, 1},
{13, 3, 3, 1},
{13, 2, 2, 1},
{13, 3, 3, 1},
{13, 5, 47, 2},
}
fmt.Println(Csum(arr...))
for k, v := range arr {
fmt.Println(k, ">>", float32(Clist(v...)))
}
fmt.Println("................")
absd := Person05{name: "fdafd"}
fmt.Println(absd.name, 133784560*21014559, math.Abs(1))
dict := make(map[int]int)
fmt.Println("ok0", dict[0])
if _, ok := dict[0]; ok {
fmt.Println("ok1", dict[0])
}
dict[0] = 0
if _, ok := dict[0]; ok {
fmt.Println("ok2", dict[0])
}
fmt.Println(dict[0], len(dict))
//countdz()
var s byte = 0
var x interface{} // x 为零值 nil,静态类型为 interface{}
x = 42 //x declared but not used // x 的值为 42,动态类型为int, 静态类型为interface{}
fmt.Println(x, s)
//var v *T // v 为零值 nil, 静态类型为 *T
//x = v // x 的值为 (*T)(nil), 动态类型为 *T, 静态类型为 *T
arrs := []int{1, 2, 3, 4}
fmt.Println(&arrs[0], &arrs[2])
slice := arrs[0:2]
fmt.Println(slice, &arrs[0], &slice[0], &arrs[2])
slice = append(slice, 8)
slice = append(slice, 9)
slice[0] = 11
slice = append(slice, 7)
slice[0] = 16
fmt.Println(slice, &arrs[0], &slice[0], &slice[2], ">>>", arrs[0], &arrs[2], "====", len(slice), cap(slice))
// bytes := hash.Sum([]byte{1,2,3,5})
// fmt.Println(CreateRandomStr("tomorrow"), hex.EncodeToString([]byte{255,16,16,16}), )
test(func() {
Exponent(3, 5)
})
test(func() {
math.Pow(3, 5)
})
tmp := [10]byte{9}
fmt.Println(tmp)
apple := -1
fmt.Println(">>>", apple<<5, maxDepth(128))
}
func maxDepth(n int) int {
var depth int
for i := n; i > 0; i >>= 1 {
depth++
}
return depth * 2
}
func GetSec() int64 {
return time.Now().UnixNano() / 10000000
}
func test(fn func()) {
tnum := GetSec()
for i := 0; i < 10000000; i++ {
fn()
}
fmt.Println(">>>", GetSec()-tnum)
}
func Exponent(a, n int64) int64 {
result := int64(1)
for i := n; i > 0; i >>= 1 {
if i&1 != 0 {
result *= a
}
a *= a
}
return result
}
//生成随机字符串//
func CreateRandomStr(seedStr string) string {
h := md5.New()
seedStr = seedStr + strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Println(seedStr)
io.WriteString(h, seedStr)
cipherStr := h.Sum(nil)
fmt.Println(cipherStr)
payNum := hex.EncodeToString(cipherStr)
return payNum
}
func saferoutine(c chan bool) {
for i := 0; i < 10; i++ {
fmt.Println("Count:", i)
time.Sleep(1 * time.Second)
}
c <- true
}
func panicgoroutine(c chan bool) {
time.Sleep(5 * time.Second)
panic("Panic, omg ...")
c <- true
}
const MaxRune = 'U0010FFFF'
const RuneError = 'uFFFD'
func TestCancelBeforeGenericEvent() {
fsm := fstate.NewFSM(
"start",
fstate.Events{
{Name: "run", Src: []string{"start"}, Dst: "end"},
},
fstate.Callbacks{
"before_event": func(e *fstate.Event) {
fmt.Println(">>>>")
e.Cancel()
},
},
)
fsm.Event("run")
if fsm.Current() != "start" {
fmt.Println("expected state to be 'start'")
}
}
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
type interf []int
func swapRange(data interf, a, b, n int) {
for i := 0; i < n; i++ {
ab := data[a+i]
data[a+i] = data[b+i]
data[b+i] = ab
}
fmt.Println(a, b, n, ">>>", data)
}
func rotate(data interf, a, m, b int) {
i := m - a
j := b - m
for i != j {
if i > j {
swapRange(data, m-i, m, j)
i -= j
} else {
swapRange(data, m-i, m+j-i, i)
j -= i
}
}
swapRange(data, m-i, m, i)
}
func Copy(re *Person04) *Person04 {
re2 := *re
return &re2
}
func outs(obj interface{}){
}
func main6996() {
// c := make(chan bool, 2)
// go saferoutine(c)
// go panicgoroutine(c)
// for i := 0; i < 2; i++ {
// <-c
// }
// fmt.Println(reflect.TypeOf(MaxRune), RuneError)
// TestCancelBeforeGenericEvent()
// list := make([]int, 8)
// for i:=0 ;i< 8;i++ {
// list[i] = i
// }
// rotate(list, 0, 3, 8)
// fmt.Println(list)
reg1 := regexp.MustCompile("a.c")
buf := "abc azc a7c aac 888 a9c tac"
result1 := reg1.FindAllStringSubmatch(buf, -1)
fmt.Println("result1 = ", result1)
//目标字符串
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
pat := "[0-9]+.[0-9]+" //正则
f := func(s string) string{
v, _ := strconv.ParseFloat(s, 32)
return strconv.FormatFloat(v * 2, 'f', 2, 32)
}
if ok, _ := regexp.Match(pat, []byte(searchIn)); ok {
fmt.Println("Match Found!")
}
re, _ := regexp.Compile(pat)
//将匹配到的部分替换为 "##.#"
str := re.ReplaceAllString(searchIn, "##.#")
fmt.Println(str)
//参数为函数时
str2 := re.ReplaceAllStringFunc(searchIn, f)
fmt.Println(str2)
s := regexp.MustCompile("a{2}").Split("baabaccadaaae", -1)
fmt.Println(s, len(s))
// s: ["", "b", "b", "c", "cadaaae"]
pat = `(((abc.)def.)ghi)`
src := `abc-def-ghi abc+def+ghi`
fmt.Println(regexp.MatchString(pat, src))
// true <nil>
fmt.Println(regexp.QuoteMeta(pat), re.String(),re.SubexpNames())
// (((abc.)def.)ghi)
}
// main6 test
func main6() {
//Path操作
// fmt.Println(path.Ext("c:\a/b.txt")) //.txt
// fmt.Println(path.IsAbs("c:/wind/aa/bb/b.txt")) //false
// fmt.Println(path.Join("c:", "aa", "bb", "cc.txt")) //c:/aa/bb/cc.txt
// isMatch, err := path.Match("c:/windows/*/", "c:/windows/system/")
// fmt.Println(isMatch, err) //true <nil>
// fmt.Println(path.Split("c:/windows/system/aaa.jpg")) //c:/windows/system/ aaa.jpg
// //FilePath操作
// fmt.Println("FilePath操作-----------------")
// fmt.Println(filepath.IsAbs("c:\wind\aa\bb\b.txt")) //true
fmt.Println(filepath.Abs(".")) //D:ProjectsGoPathsourcedemosyntaxpath <nil>
// filepath.Walk("../", WalkFunc)
/*
File: ../../syntax IsDir: true size: 0
File: ....syntaxpainc IsDir: true size: 0
File: ....syntaxpaincmain.go IsDir: false size: 813
File: ....syntaxpaincpainc.exe IsDir: false size: 2498048
File: ....syntaxpath IsDir: true size: 0
File: ....syntaxpathpath.exe IsDir: false size: 2851328
File: ....syntaxpathpath.go IsDir: false size: 3419
*/
// tepl := "My name is {{ . }}"
// // 解析模板
// tmpl, err := text.New("test").Parse(tepl)
// // 数据驱动模板
// data := "jack"
// err = tmpl.Execute(os.Stdout, data)
w := tabwriter.NewWriter(os.Stdout, 10, 1, 5, '*', 0)
defer w.Flush()
// show := func(name string, v1, v2, v3 interface{}) {
// fmt.Fprintf(w, "%s %v %v %v
", name, v1, v2, v3)
// }
//show("Int31",11111111111,2,2222223)
// Gosched:让当前线程让出 cpu 以让其它线程运行,它不会挂起当前线程,因此当前线程未来会继续执行
// NumCPU:返回当前系统的 CPU 核数量
// GOMAXPROCS:设置最大的可同时使用的 CPU 核数
// Goexit:退出当前 goroutine(但是defer语句会照常执行)
// NumGoroutine:返回正在执行和排队的任务总数
// GOOS:目标操作系统
fmt.Println("cpus:", runtime.NumCPU(), runtime.NumGoroutine())
fmt.Println("goroot:", runtime.GOROOT())
fmt.Println("archive:", runtime.GOOS)
//runtime.Goexit()
//runtime.GOMAXPROCS(1) //使用单核
exit := make(chan int)
go func() {
defer close(exit)
go func() {
fmt.Println("b")
}()
}()
for i := 0; i < 4; i++ {
fmt.Println("a:", i)
if i == 1 {
runtime.Gosched() //切换任务
}
}
<-exit
// go say("world")
// say("hello")
}
type T int
func IsClosed(ch <-chan T) bool {
select {
case <-ch:
return true
default:
}
return false
}
func main1112() {
c := make(chan T)
fmt.Println(IsClosed(c)) // false
close(c)
fmt.Println(IsClosed(c)) // true
}
func say(s string){
for i := 0; i < 2; i++ {
runtime.Gosched()
fmt.Println(s)
}
}
func WalkFunc(path string, info os.FileInfo, err error) error {
fmt.Println("File:", path, "IsDir:", info.IsDir(), "size:", info.Size())
return nil
}
func main1158() {
rand.Seed(time.Now().UnixNano())
log.SetFlags(0)
// ...
const MaxRandomNumber = 100000
const NumReceivers = 10
const NumSenders = 1000
wgReceivers := sync.WaitGroup{}
wgReceivers.Add(NumReceivers)
// ...
dataCh := make(chan int, 100)
stopCh := make(chan struct{})
// stopCh is an additional signal channel.
// Its sender is the moderator goroutine shown below.
// Its reveivers are all senders and receivers of dataCh.
toStop := make(chan string, 1)
// the channel toStop is used to notify the moderator
// to close the additional signal channel (stopCh).
// Its senders are any senders and receivers of dataCh.
// Its reveiver is the moderator goroutine shown below.
var stoppedBy string
// moderator
go func() {
stoppedBy = <- toStop // part of the trick used to notify the moderator
// to close the additional signal channel.
close(stopCh)
}()
// senders
for i := 0; i < NumSenders; i++ {
go func(id string) {
for {
value := rand.Intn(MaxRandomNumber)
if value == 0 {
// here, a trick is used to notify the moderator
// to close the additional signal channel.
select {
case toStop <- "sender#" + id:
default:
}
return
}
// the first select here is to try to exit the
// goroutine as early as possible.
select {
case <- stopCh:
return
default:
}
select {
case <- stopCh:
return
case dataCh <- value:
}
}
}(strconv.Itoa(i))
}
// receivers
for i := 0; i < NumReceivers; i++ {
go func(id string) {
defer wgReceivers.Done()
for {
// same as senders, the first select here is to
// try to exit the goroutine as early as possible.
select {
case <- stopCh:
return
default:
}
select {
case <- stopCh:
return
case value := <-dataCh:
if value == MaxRandomNumber-1 {
// the same trick is used to notify the moderator
// to close the additional signal channel.
select {
case toStop <- "receiver#" + id:
default:
}
return
}
log.Println(value)
}
}
}(strconv.Itoa(i))
}
// ...
wgReceivers.Wait()
log.Println("stopped by", stoppedBy)
}
func request(timeout time.Duration) (Response, error) {
//用于触发超时的上下文
deadline := time.Now().Add(timeout)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
//用于接收IO响应的通道
respCh := make(chan string)
start := time.Now()
//另起goroutine执行IO操作
go doIO(respCh)
var respData Response
var err error
//如果先接收到响应则停掉超时计时器
//如果超时计时器先触发,则生成一个error的实例
select {
case respData.body = <-respCh:
case <-ctx.Done():
err = errors.New("request timeout")
}
//记录总耗时
respData.elapse = time.Now().Sub(start)
return respData, err
}
type Response struct {
body string //响应内容
elapse time.Duration //响应耗时
}
func requestS(timeout time.Duration) (Response, error) {
//用于触发超时的计时器
timer := time.NewTimer(timeout)
//用于接收IO响应的通道
respCh := make(chan string)
start := time.Now()
//另起goroutine执行IO操作
go doIO(respCh)
var respData Response
var err error
//如果先接收到响应则停掉超时计时器
//如果超时计时器先触发,则生成一个error的实例
select {
case respData.body = <-respCh:
timer.Stop()
case <-timer.C:
err = errors.New("request timeout")
}
//记录总耗时
respData.elapse = time.Now().Sub(start)
return respData, err
}
func doIO(respCh chan string) {
//随机产生一个[0,100)毫秒的延迟,以模拟IO延时延迟
rand.Seed(time.Now().UnixNano())
delay := time.Duration(rand.Intn(100)) * time.Millisecond
fmt.Printf("delay=%v
", delay)
time.Sleep(delay)
respCh <- "Hello World"
}
func mainTEST() {
resp, err := request(50 * time.Millisecond)
if err != nil {
fmt.Printf("error: %s
", err.Error())
return
}
fmt.Printf("response: body=%s elapse=%s
", resp.body, resp.elapse)
}
//worker工作的最大时长,超过这个时长worker自行收工无需等待manager叫停
const MAX_WORKING_DURATION = 5 * time.Second
//达到实际工作时长后,manager可以提前叫停
const ACTUAL_WORKING_DURATION = 2 * time.Second
func add(logs *[]int, lock *sync.Mutex, log int){
lock.Lock()
fmt.Println(">>>", log)
logs = append(logs, log)
lock.Unlock()
}
func qiess(logs []int) {
logs[0] = 99
for i := 0; i<10; i++ {
logs = append(logs, i)
fmt.Printf("%p", logs)
fmt.Println(" ",logs)
}
}
func print(para ...interface{}) {
fmt.Println(para...)
}
func worker1(ch chan struct{}, name string) {
for {
// select {
// case <-ch:
// fmt.Println(name, "return for ctxWithCancel.Done()")
// return
// default:
// fmt.Println(name, "working")
// }
time.Sleep(2 * time.Second)
}
}
func slaver(ch chan int){
//time.Sleep(1 * time.Second)
print(">>>>>0")
ch<-0
print(">>>>>1")
ch<-0
print(">>>>>2")
<-ch
print(">>>>>20")
ch<-0
print(">>>>>30")
}
func onec(ch chan int){
print("onec>>>>>1")
ch<-0
print("onec>>>>>2")
}
func mainfi12(){
chs := make(chan int)
print(">>>>>>>>>>>>")
go slaver(chs)
time.Sleep(1 * time.Second)
print(">>>>>>3")
<-chs
print(">>>>>>4")
<-chs
print(">>>>>>40")
//time.Sleep(1 * time.Second)
print(">>>>>>5")
}
func mainfis() {
var lock sync.Mutex
ch := make(chan int)
logs := make([]int, 0)
go slaver(ch) //go manager(ch, &logs, &lock)
add(&logs, &lock, 1)
<-ch
add(&logs, &lock, 2)
time.Sleep(1 * time.Second)
add(&logs, &lock, 3)
fmt.Println("gogo ", logs)
}
func manager(ch chan int, logs *[]int, lock *sync.Mutex) {
time.Sleep(1 * time.Second)
add(logs, lock, 4)
ch<- 0 //A
add(logs, lock, 5)
ch<- 0 //B
add(logs, lock, 6)
ch<- 0 //C
}
type MyChannel struct {
C chan T
once sync.Once
}
func NewMyChannel() *MyChannel {
return &MyChannel{C: make(chan T)}
}
func (mc *MyChannel) SafeClose() {
mc.once.Do(func(){
close(mc.C)
})
}
func takes() {
rand.Seed(time.Now().UnixNano())
log.SetFlags(0)
// ...
const MaxRandomNumber = 10
const NumReceivers = 2
wgReceivers := sync.WaitGroup{}
wgReceivers.Add(NumReceivers)
// ...
dataCh := make(chan int, NumReceivers)
// the sender
go func() {
for {
if value := rand.Intn(MaxRandomNumber); value == 110 {
// the only sender can close the channel safely.
close(dataCh)
return
} else {
print("<<1<", value)
dataCh <- value
print("<<2<", value)
}
time.Sleep(time.Second)
}
}()
// receivers
for i := 0; i < NumReceivers; i++ {
go func(i int) {
time.Sleep(time.Second)
defer wgReceivers.Done()
// receive values until dataCh is closed and
// the value buffer queue of dataCh is empty.
print(">>>>>>>>>>>>>", i)
for value := range dataCh {
print(">>>>>[", i,"]", value)
}
}(i)
}
wgReceivers.Wait()
}
func mainfissss(){
var C chan int
C = make(chan int)
var once sync.Once
once.Do(func(){
fmt.Println("zzzz")
close(C)
})
// go func() {
// for {
// if value := rand.Intn(10); value == 0 {
// // the only sender can close the channel safely.
// close(C)
// return
// } else {
// C <- value
// }
// }
// }()
fmt.Println("zzzz")
takes()
}
func mainfiff() {
rand.Seed(time.Now().UnixNano())
log.SetFlags(0)
// ...
const MaxRandomNumber = 100000
const NumReceivers = 10
const NumSenders = 1000
wgReceivers := sync.WaitGroup{}
wgReceivers.Add(NumReceivers)
// ...
dataCh := make(chan int, 100)
stopCh := make(chan struct{})
// stopCh is an additional signal channel.
// Its sender is the moderator goroutine shown below.
// Its reveivers are all senders and receivers of dataCh.
toStop := make(chan string, 1)
// the channel toStop is used to notify the moderator
// to close the additional signal channel (stopCh).
// Its senders are any senders and receivers of dataCh.
// Its reveiver is the moderator goroutine shown below.
var stoppedBy string
// moderator
go func() {
stoppedBy = <- toStop // part of the trick used to notify the moderator
// to close the additional signal channel.
close(stopCh)
}()
// senders
for i := 0; i < NumSenders; i++ {
go func(id string) {
for {
value := rand.Intn(MaxRandomNumber)
if value == 0 {
// here, a trick is used to notify the moderator
// to close the additional signal channel.
select {
case toStop <- "sender#" + id:
default:
}
return
}
// the first select here is to try to exit the
// goroutine as early as possible.
select {
case <- stopCh:
return
default:
}
select {
case <- stopCh:
return
case dataCh <- value:
}
}
}(strconv.Itoa(i))
}
// receivers
for i := 0; i < NumReceivers; i++ {
go func(id string) {
defer wgReceivers.Done()
for {
// same as senders, the first select here is to
// try to exit the goroutine as early as possible.
select {
case <- stopCh:
return
default:
}
select {
case <- stopCh:
return
case value := <-dataCh:
if value == MaxRandomNumber-1 {
// the same trick is used to notify the moderator
// to close the additional signal channel.
select {
case toStop <- "receiver#" + id:
default:
}
return
}
log.Println(value)
}
}
}(strconv.Itoa(i))
}
// ...
wgReceivers.Wait()
log.Println("stopped by", stoppedBy)
}
const MAIL_LIST = "MAIL_LIST"
func get() (ret int64) {
return
}
type pial struct{
Uid int32
List []int32
}
var nameList []string
var pickdata int32
func getpick()(int32,int32){
return 2,10
}
func updatepick() int32{
pickdata = 30
pickdata, err := getpick()
pickdata++
return pickdata + err
}
type datatry struct {
List []int json:"list"
}
var nowd datatry
func getnow()(fill datatry){
print(fill)
return
}
func mainfiqq() {
var t time.Time
var list []int = []int{1,2,3}
num := 10
gos := func()int{
num = RandInt(10)
return num
}
for i:= 0; i< gos() ;i++{
print(i, num)
}
print(t.String(), MAIL_LIST +"sadfkljasd", list[:0])
print( get())
pic := int64(10000)
pic = pic*pic
print(pic)
obj := pial{Uid: 0}
ls := &obj.List
*ls = append(*ls, 1,2)
print(*ls, obj)
lp := obj.List
lp[1] = 999
lp = append(lp[:0], lp[1:]...)
print(*ls, obj, lp)
print(nameList)
nameList = append(nameList, "gogo")
print(nameList)
print(pickdata)
updatepick()
print(pickdata, nowd.List, &(&nowd).List)
getnow()
// "2006-01-02", // RFC 3339
// "2006-01-02 15:04", // RFC 3339 with minutes
// "2006-01-02 15:04:05", // RFC 3339 with seconds
// "2006-01-02 15:04:05-07:00", // RFC 3339 with seconds and timezone
// "2006-01-02T15Z0700", // ISO8601 with hour
// "2006-01-02T15:04Z0700", // ISO8601 with minutes
// "2006-01-02T15:04:05Z0700", // ISO8601 with seconds
// "2006-01-02T15:04:05.999999999Z0700", // ISO8601 with nanoseconds
datetime := "2015-01-01 02:15:03" //待转化为时间戳的字符串
//日期转化为时间戳
timeLayout := "2006-01-02 15:05:15" //转化所需模板
loc, _ := time.LoadLocation("Local") //获取时区
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
timestamp := tmp.Unix() //转化为时间戳 类型是int64
fmt.Println(timestamp)
print(time.Unix(1606444036+120,0))
print(strings.Count("asdfasdf","s"))
//时间戳转化为日期
datetime = time.Unix(timestamp, 0).Format(timeLayout)
fmt.Println(datetime)
testfn := func(str string) {
datetime = fmt.Sprintf("%s", time.Unix(int64(1000), 0).Format(str))
print(datetime)
}
testfn("01-02-2006 15:04:05")
testfn("01-02-0006 00022:04:05")
print(strings.Split("01020006", "-"))
// func (re *Regexp) ReplaceAllString(src, repl string) string
// func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
// func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
// ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$
// 分开来注释一下:
// ^ 匹配一行的开头位置
// (?![0-9]+$) 预测该位置后面不全是数字
// (?![a-zA-Z]+$) 预测该位置后面不全是字母
// [0-9A-Za-z] {8,16} 由8-16位数字或这字母组成
// $ 匹配行结尾位置
pat := `([A-Za-z0-9]+)s*=s*([A-Za-z0-9]+)`
src := ` abc = d23 abc1 = f456 `
reg := regexp.MustCompile(pat)
put := reg.ReplaceAllStringFunc(src, func(str string) string {
print(str)
return str+"end"
})
print(put)
lss := reg.FindAllStringSubmatch(src, -1)
print(lss)
pats := `(<cr:[f0-9]{6}>([a-zA-Z0-9])</>)`
regs := regexp.MustCompile(pats)
strco := `ni mail to this <cr:ff3ff6>sdfasd</>mm`
lsss := regs.FindAllStringSubmatch(strco, -1)
print(lsss)
print(strconv.QuoteToASCII("u597adasdf你好fas12"))
print("-----------")
hasWord("u597adasdf你好fas12")
}
// 一般字符 匹配自身 abc abc
// . 匹配任意除换行符"
"外的字符, 在 DOTALL 模式中也能匹配换行符 a.c abc
// 转义字符,使后一个字符改变原来的意思;
// 如果字符串中有字符 * 需要匹配,可以使用 * 或者字符集[]。 a.c
// ac a.c
// ac
// [...] 字符集(字符类),对应的位置可以是字符集中任意字符。
// 字符集中的字符可以逐个列出,也可以给出范围,如 [abc] 或 [a-c],
// 第一个字符如果是 ^ 则表示取反,如 [^abc] 表示除了abc之外的其他字符。 a[bcd]e abe 或 ace 或 ade
// d 数字:[0-9] adc a1c
// D 非数字:[^d] aDc abc
// s 空白字符:[<空格>
fv] asc a c
// S 非空白字符:[^s] aSc abc
// w 单词字符:[A-Za-z0-9] awc abc
// W 非单词字符:[^w] aWc a c
// 2) 数量词(用在字符或 (...) 之后)
// 语法 说明 表达式示例 匹配结果
// * 匹配前一个字符 0 或无限次 abc ab 或 abccc
// + 匹配前一个字符 1 次或无限次 abc+ abc 或 abccc
// ? 匹配前一个字符 0 次或 1 次 abc? ab 或 abc
// {m} 匹配前一个字符 m 次 ab{2}c abbc
// {m,n} 匹配前一个字符 m 至 n 次,m 和 n 可以省略,若省略 m,则匹配 0 至 n 次;
// 若省略 n,则匹配 m 至无限次 ab{1,2}c abc 或 abbc
// 3) 边界匹配
// 语法 说明 表达式示例 匹配结果
// ^ 匹配字符串开头,在多行模式中匹配每一行的开头 ^abc abc
// $ 匹配字符串末尾,在多行模式中匹配每一行的末尾 abc$ abc
// A 仅匹配字符串开头 Aabc abc
// 仅匹配字符串末尾 abc abc
// 匹配 w 和 W 之间 a!bc a!bc
// B [^] aBbc abc
// 4) 逻辑、分组
// 语法 说明 表达式示例 匹配结果
// | | 代表左右表达式任意匹配一个,优先匹配左边的表达式 abc|def abc 或 def
// (...) 括起来的表达式将作为分组,分组将作为一个整体,可以后接数量词 (abc){2} abcabc
// (?P
// <number> 引用编号为
// (?P=name) 引用别名为
// 5) 特殊构造(不作为分组)
// 语法 说明 表达式示例 匹配结果
// (?:...) (…) 的不分组版本,用于使用 "|" 或后接数量词 (?:abc){2} abcabc
// (?iLmsux) iLmsux 中的每个字符代表一种匹配模式,只能用在正则表达式的开头,可选多个 (?i)abc AbC
// (?#...) # 后的内容将作为注释被忽略。 abc(?#comment)123 abc123
// (?=...) 之后的字符串内容需要匹配表达式才能成功匹配 a(?=d) 后面是数字的 a
// (?!...) 之后的字符串内容需要不匹配表达式才能成功匹配 a(?!d) 后面不是数字的 a
// (?<=...) 之前的字符串内容需要匹配表达式才能成功匹配 (?<=d)a 前面是数字的a
// (?<!...) 之前的字符串内容需要不匹配表达式才能成功匹配 (?<!d)a 前面不是数字的a
func hasWord(str string) {
txt := "abs123abs1234dfs32kkkl54"
//txt = strconv.QuoteToASCII(txt)
print(txt)
pat := ``
reg := regexp.MustCompile(pat)
ret := reg.FindAllStringSubmatch(txt, -1)
print(ret)
reg.ReplaceAllStringFunc2(txt, func(str []string) string {
print(str)
return str[0]
})
}
func (re Regexp) ReplaceAllStringFunc2(src string, repl func([]string) string) string {
b := re.replaceAll(nil, src, re.prog.NumCap, func(dst []byte, match []int) []byte {
slice := make([]string, len(match)/2)
for j := range slice {
if match[2j] >= 0 {
slice[j] = src[match[2j]:match[2j+1]]
}
}
return append(dst, repl(slice)...)
})
return string(b)
}
func replaceFunc(s []string) string {
n := 0
for i := 1; i < len(s); i++ {
ret, _ := strconv.Atoi(s[i])
n += ret
}
return strconv.Itoa(n)
}
func mainfi(){
repl := "1,10 1,50,12 1,12,5 1,20 1,3,2 "
place := regexp.MustCompile("(d+),(d+),(d+)").ReplaceAllStringFunc2
repl = place(repl, replaceFunc)
fmt.Println(repl)
}
// FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it
// returns a slice of all successive matches of the expression, as defined by
// the 'All' description in the package comment.
// A return value of nil indicates no match.
`