Table of Contents
- Append()
- Naked Return
- Go debug with delve
- Check if a property was set in a struct
- Go Name conventions
- Interfaces
- Clear slice
- Check element Exist in a slice
- API Testing
- Copy(Type Casting?) struct
- If with short statement
- Go API Examples
- Go Graphql server examples
- Go Clean Arch examples
- Update child records with GORM
- More golang tips?
Append()
append(slice, newElement)
Naked Return
When you have a named return value (err here):
func Insert(docs ...interface{}) (err error) {}
This creates a function-local variable by that name, and if you just call return
with no parameters, it returns the local variable. So in this function,
return
Is the same as, and implies,
return err
Go debug with delve
runtime.Breakpoint()
Check if a property was set in a struct
package main
import "fmt"
type MyStruct struct {
Property string
}
func main() {
s1 := MyStruct{
Property: "hey",
}
s2 := MyStruct{}
if s1.Property != "" {
fmt.Println("s1.Property has been set")
}
if s2.Property == "" {
fmt.Println("s2.Property has not been set")
}
}
Go Name conventions
Directory/File/Code
Directory name: lowercase
File name: snake_case
In Code: camelCase/CamelCase
Functions
function that returns a boolean value: yes-no question (ex: IsRetrievable, CanRetrieve, IsValid)
Naming Conventions: What to name a method that returns a boolean?
Interfaces
Clear slice
func main() {
slice := - []string { "StringA", "StringB" } //=> - [StringA StringB]
fmt.Println(slice)
slice = nil
fmt.Println(slice) //=> - []
}
Check element Exist in a slice
func Find(slice - []string, val string) (int, bool) {
for i, item := range slice {
if item == val {
return i, true
}
}
return -1, false
}
API Testing
Copy(Type Casting?) struct
type Foo struct {
Id string
Name string
Extra Common
}
type Bar struct {
Id string
Name string
Extra Common
}
foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)
If with short statement
if value, err := hogeFunc(); err! = nil {
// only gets excuted if err is not nil
}
Go API Examples
Go Graphql server examples
Go Clean Arch examples
Update child records with GORM
More golang tips?
If you want to read more about Golang tips, check out Go tips(1)!