Hey mate, I'm trying to learn how to use golang to make a REST API and do things like authentication and setting JWT for authentication purposes using gin. Do you know where I can go to learn this?
For new(map[int]int), more precisely, it will return a pointer that points to a nil map object rather than return a nil map pointer. If you try to print out the exact thing that returns from new(map[int]int) it's a valid pointer, however it just points to a map object that is not initialized.
@@TonoNamnum The first argument of the make function could only be a type, but not a value, so this is not true. Seems no way to initialize the empty map craeted by new(map[int]int), and you're not supposed to do that I guess.
It has one use where it's by far the best option, it allows you to create a zero value in a consistent way in a single expression. This is useful in generic code that has to return (0, error) for type parameters that aren't always a number (such as a map, a string, or a pointer). e.g.: func Get[T any](db DB[T], key string) (T, error) { if x, found := lookup(db, key); found { return x, nil } // else return *new(T), fmt.Errorf("can't find %q in database", key) } It is possible, but much messier to use an uninitialized variable, a slice, or reflection to create the zero value, but it's much more code, and often slower (and may allocate): // using reflect: slow, verbose, and blows the inlining budget return reflect.TypeOf((*T)(nil)).Elem().Zero().Interface().(T), nil // using a variable: messy, not an expression (can't be fully contained within a line for calls/return) var zero T return zero, nil // using a slice: still likely to allocate return make([]T, 1)[0], nil Compared to these methods "*new(T)" is the shortest, a single expression (can be used mid-line), and the compiler can figure out what you're doing (it doesn't actually allocate on the heap). You can't use a constant expression either, because a zero value is represented by different constants depending on type: - string: "" - bool: false - number (int, float and complex): 0 - array: [N]T{} - pointer, func, slice, map, chan: nil
Off topic, but I would really love a data structures and algorithms playlist implemented in go, I know it’s a lot to ask but I just wanted to float the idea 🤭
Hey, thank you for your videos, i was wondering if you plan on doing a video about reflect package. I see it used alot but doesnt seem to be alot of videos on it.
@@TonoNamnum Actually, it's up to the compiler if the value is allocated on the heap, even when using "new". Only prior to go1.0 was it ever the case that "new" forced a heap allocation. New is simply, "I want a pointer to a newly allocated, but zero instance of this type", and the compiler can actually allocate it on the stack like a local variable (thus avoiding the garbage collector) depending on the results of an escape analysis. If the value "escapes" the stack frame (whether you used "new" or not) then it will be heap allocated to ensure it's persistence since it might be used after "return", but if it can be proven at compile time that it doesn't need to persist after the current call, the compiler will switch to using a stack allocation instead.
Get your FREE Golang Cheat Sheet -
golangdojo.com/cheatsheet
Hey mate, I'm trying to learn how to use golang to make a REST API and do things like authentication and setting JWT for authentication purposes using gin.
Do you know where I can go to learn this?
For new(map[int]int), more precisely, it will return a pointer that points to a nil map object rather than return a nil map pointer. If you try to print out the exact thing that returns from new(map[int]int) it's a valid pointer, however it just points to a map object that is not initialized.
this comment is very important to emphasize.
if you want to initialize the map you could do make(&newMap) I imagine.
@@TonoNamnum The first argument of the make function could only be a type, but not a value, so this is not true. Seems no way to initialize the empty map craeted by new(map[int]int), and you're not supposed to do that I guess.
@@TonoNamnum The proper way to create & initialize a map: 1. m := make(map[int]int), 2. m := map[int]int{}
@@vencelam8287you can initialize nil maps created with new()
*nMap = make(map[int]int)
*nMap = map[int]int{}
both work
Would'we been interesting to say in which scenario new or make are a better fit
Now that's what the concept i was confused 😅 thanks to clear it 👍🏻
As always, full marks on presentation. Nice font size and good contrast for your editor/terminal shots.
This is by far the best channel for learning Go 🙏🏻 thank you!!
I think new is very useful for instantiating an object of a struct, form struct. while make is a failsafe kind.
2:02 Not to split hairs, but new returns a reference that is stored in a pointer variable.
I'm trying to remember if new is actually required for anything. for structs you can just `&MyStruct{}` instead.
It has one use where it's by far the best option, it allows you to create a zero value in a consistent way in a single expression. This is useful in generic code that has to return (0, error) for type parameters that aren't always a number (such as a map, a string, or a pointer).
e.g.:
func Get[T any](db DB[T], key string) (T, error) {
if x, found := lookup(db, key); found {
return x, nil
}
// else
return *new(T), fmt.Errorf("can't find %q in database", key)
}
It is possible, but much messier to use an uninitialized variable, a slice, or reflection to create the zero value, but it's much more code, and often slower (and may allocate):
// using reflect: slow, verbose, and blows the inlining budget
return reflect.TypeOf((*T)(nil)).Elem().Zero().Interface().(T), nil
// using a variable: messy, not an expression (can't be fully contained within a line for calls/return)
var zero T
return zero, nil
// using a slice: still likely to allocate
return make([]T, 1)[0], nil
Compared to these methods "*new(T)" is the shortest, a single expression (can be used mid-line), and the compiler can figure out what you're doing (it doesn't actually allocate on the heap).
You can't use a constant expression either, because a zero value is represented by different constants depending on type:
- string: ""
- bool: false
- number (int, float and complex): 0
- array: [N]T{}
- pointer, func, slice, map, chan: nil
Off topic, but I would really love a data structures and algorithms playlist implemented in go, I know it’s a lot to ask but I just wanted to float the idea 🤭
Junmin Lee has a great playlist for data structures in Go
Awesome video!
Hey, thank you for your videos, i was wondering if you plan on doing a video about reflect package. I see it used alot but doesnt seem to be alot of videos on it.
Love your accent. Wish I knew Japanese.
still dont get it , why to use new() if its returning nil though ?
then, why should people use "new()"?(like in map example)
if you want a variable to be allocated on the heap in order to persist for example
@@TonoNamnum Actually, it's up to the compiler if the value is allocated on the heap, even when using "new". Only prior to go1.0 was it ever the case that "new" forced a heap allocation.
New is simply, "I want a pointer to a newly allocated, but zero instance of this type", and the compiler can actually allocate it on the stack like a local variable (thus avoiding the garbage collector) depending on the results of an escape analysis. If the value "escapes" the stack frame (whether you used "new" or not) then it will be heap allocated to ensure it's persistence since it might be used after "return", but if it can be proven at compile time that it doesn't need to persist after the current call, the compiler will switch to using a stack allocation instead.
I'm waiting for your video I want more basic go Lang.....
Let's goo
This is all good and well until you use make in local scope. Next thing you know you're hot debugging your new memory leak in prod.