From cb533946f4f65bacc405091d53a71c1f5c9362d6 Mon Sep 17 00:00:00 2001 From: Hau Nguyen Date: Sun, 24 Sep 2023 19:30:39 +0700 Subject: [PATCH] go: generics tricks --- docs/2022-07-10-bootstrap-go.html | 27 +++++++++++++++++++++++++++ posts/2022-07-10-bootstrap-go.md | 12 ++++++++++++ 2 files changed, 39 insertions(+) diff --git a/docs/2022-07-10-bootstrap-go.html b/docs/2022-07-10-bootstrap-go.html index d6279c9..60ed1cc 100644 --- a/docs/2022-07-10-bootstrap-go.html +++ b/docs/2022-07-10-bootstrap-go.html @@ -320,6 +320,26 @@ internal result := make([]byte, b.Len()) copy(result, b.Bytes()) return result, nil +} + +

+ Generics + with some tricks +

+

+ Take value then return pointer, useful with database struct full of + pointers: +

+
+
// Ptr takes in non-pointer and returns a pointer
+func Ptr[T any](v T) *T {
+	return &v
 }

@@ -856,6 +876,13 @@ fieldalignment -fix ./internal/business/*.go >Advanced Go Concurrency +
  • + Go generic: non-ptr to ptr +
  • diff --git a/posts/2022-07-10-bootstrap-go.md b/posts/2022-07-10-bootstrap-go.md index c5dba19..5a315e8 100644 --- a/posts/2022-07-10-bootstrap-go.md +++ b/posts/2022-07-10-bootstrap-go.md @@ -190,6 +190,17 @@ func MarshalWithoutEscapeHTML(v any) ([]byte, error) { } ``` +### [Generics](https://go.dev/doc/tutorial/generics) with some tricks + +Take value then return pointer, useful with database struct full of pointers: + +```go +// Ptr takes in non-pointer and returns a pointer +func Ptr[T any](v T) *T { + return &v +} +``` + ## External libs ### No need `vendor` @@ -486,3 +497,4 @@ go clean -cache -testcache -modcache -fuzzcache -x - [Speed Up GoMock with Conditional Generation](https://jonwillia.ms/2019/12/22/conditional-gomock-mockgen) - [Making SQLite faster in Go](https://turriate.com/articles/making-sqlite-faster-in-go) - [Advanced Go Concurrency](https://encore.dev/blog/advanced-go-concurrency) +- [Go generic: non-ptr to ptr](https://danielms.site/zet/2023/go-generic-non-ptr-to-ptr/)