比较骚的一些代码

比较骚的一些代码

操作系统表情包

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
func osEmoji(os string) string {
	switch os {
	case "linux":
		return "🐧"
	case "macOS":
		return "🍎"
	case "windows":
		return "🖥️"
	case "iOS":
		return "📱"
	case "android":
		return "🤖"
	case "freebsd":
		return "👿"
	case "openbsd":
		return "🐡"
	}
	return "👽"
}

文件自动重命名

1
2
3
for i := 1; gfile.Exists(dst); i++ {
	dst = gfile.Join(dir, fmt.Sprintf(fmt.Sprintf("%s(%d)%s", gfile.Name(in.File.Filename), i, gfile.Ext(in.File.Filename))))
}

编译环境检查

1
2
3
4
5
//go:build go1.21

package qtls

var _ int = "The version of quic-go you're using can't be built on Go 1.21 yet. For more details, please see https://github.com/quic-go/quic-go/wiki/quic-go-and-Go-versions."

函数定义

1
2
3
4
5
6
7
8
9
type st struct{}

func (s *st) name(string) {}

var (
	handles = []func(*st, string){
		(*st).name,
	}
)

嵌套取值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
	"fmt"
)

type I1 interface {
	Name() string
}

type T1 struct{}

func (t *T1) Name() string {
	return "t1"
}

func (t *T1) Age() int {
	return 18
}

type T2 struct {
	I1
}

func (t *T2) Name() string {
	return t.I1.Name() + " t2"
}

func Fn(t I1) {
	fmt.Println(t.Name())
	fmt.Println(t.(*T2).I1.(*T1).Age())
}

func main() {
	t1 := &T1{}
	t2 := &T2{I1: t1}
	Fn(t2)
}

字符串 <-> []byte

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package util

import (
	"unsafe"
)

// BytesToString converts byte slice to string.
func BytesToString(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

// StringToBytes converts string to byte slice.
func StringToBytes(s string) []byte {
	return *(*[]byte)(unsafe.Pointer(
		&struct {
			string
			Cap int
		}{s, len(s)},
	))
}

切片截取性能优化

1
2
// 性能优于 buf1 := buf[:length]
buf1 := buf[:uint32(length)]
Licensed under CC BY-NC-SA 4.0
最后更新于 Dec 16, 2024 15:37 +0800
使用 Hugo 构建
主题 StackJimmy 设计