跳转至
阅读量:

比较骚的一些代码

操作系统表情包

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 "👽"
}

文件自动重命名

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))))
}

编译环境检查

//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."

函数定义

type st struct{}

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

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

嵌套取值

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

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)},
    ))
}

评论