nstd وحدة go ذات حزمة واحدة توفّر بعض الأنواع والدوال المفقودة في المكتبة القياسية.
صفحة المشروع: https://github.com/go101/nstd
صفحة التوثيق: https://docs.go101.org/std/pkg/go101.org/nstd.html
مسار الوحدة: go101.org/nstd
تابع @zigo_101 للحصول على آخر أخبار nstd (وكل أنواع تفاصيل/حقائق/نصائح Go...).
بعض الأمثلة على استخدام nstd
المثال 1:
package main
import (
"go101.org/nstd"
"log"
)
const debug = true
const foo = "foo"
func debugPrint(s string) {
if debug {
log.Print(s)
}
}
func main() {
var bar = "bar"
_ = debug && nstd.Logf(foo + ":" + bar)
// إنه أنظف من
// if debug {
// log.Print(foo + " " + bar)
// }
//
// وهو أعلى أداءً من
// debugPrint(foo + " " + bar)
// عندما تكون debug مساوية false.
}
المثال 2:
package main
import (
"go101.org/nstd"
)
func ExampleMutexAndWaitGroup() {
const N = 1000
var n = 0
defer func() {
nstd.Printfln("n = %d", n) // سيطبع سطراً جديداً في النهاية
if expected := N*7; n != expected {
nstd.Panicf("n (%d) != %d", n, expected) // panic مع تنسيق
}
}()
var wg nstd.WaitGroup
defer wg.Wait()
var m nstd.Mutex
for range [1000]struct{}{} {
// تبدأ WaitGroup.Go عدة مهام.
wg.Go(func() {
defer m.Lock().Unlock() // استدعِ Lock وUnlock بسلسلة
n += 2
}, func() {
defer m.Lock().Unlock()
n += 1
})
// تبدأ WaitGroup.GoN مهمة واحدة عدة مرات.
wg.GoN(3, func() {
defer m.Lock().Unlock()
n += 1
})
}
// تحرس Mutex.Do تنفيذ دالة.
m.Do(func() {
n += N
})
}
func main() {
ExampleMutexAndWaitGroup()
}
المثال 3:
package main
import (
"go101.org/nstd"
)
func main() {
pInt := nstd.New(123)
nstd.Printfln("%T: %v", pInt, *pInt) // *int: 123
pBool := nstd.New(true)
nstd.Printfln("%T: %v", pBool, *pBool) // *bool: true
nstd.Printfln("%v", nstd.ZeroOf[int]()) // 0
nstd.Printfln("%v", nstd.ZeroOf[bool]()) // false
nstd.Zero(pInt)
nstd.Printfln("%v", *pInt) // 0
nstd.Zero(pBool)
nstd.Printfln("%v", *pBool) // false
}
المثال 4:
package main
import (
"go101.org/nstd"
)
func main() {
var aCondition = true
var m = map[string]int{"Zig": 2016}
_ = aCondition && nstd.HasEntry(m, "Go")
// وبذلك، لا حاجة لكتابته في سطرين:
// _, ok := m["Go"]
// _ = aCondition && ok
var x any = 123
var n int
_ = aCondition && nstd.TypeAssert(x, &n)
// وبذلك، لا حاجة لكتابته في سطرين:
// n, ok := x.(int)
// _ = aCondition && ok
nstd.Printfln("n = %v", n) // n = 123
_ = aCondition && nstd.TypeAssert[int](x, nil)
_ = aCondition && nstd.TypeAssert(x, (*int)(nil))
}
المثال 5:
package main
import (
"reflect"
"go101.org/nstd"
)
func main() {
var n int = 123
var x any = n
nstd.Printfln("type of x: %s", reflect.TypeOf(x)) // type of x: int
nstd.Printfln("type of x: %s", nstd.TypeOf(x)) // type of x: interface {}
nstd.Printfln("type of x: %s", reflect.ValueOf(x).Type()) // type of x: int
nstd.Printfln("type of x: %s", nstd.ValueOf(x).Type()) // type of x: interface {}
}