make() vs new() - Similarities & Differences

Поділитися
Вставка
  • Опубліковано 22 сер 2024

КОМЕНТАРІ • 27

  • @GolangDojo
    @GolangDojo  2 роки тому +2

    Get your FREE Golang Cheat Sheet -
    golangdojo.com/cheatsheet

    • @scottmcmahon7209
      @scottmcmahon7209 2 роки тому

      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?

  • @vencelam8287
    @vencelam8287 2 роки тому +23

    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
      @TonoNamnum 2 роки тому +2

      this comment is very important to emphasize.
      if you want to initialize the map you could do make(&newMap) I imagine.

    • @vencelam8287
      @vencelam8287 2 роки тому +1

      @@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.

    • @vencelam8287
      @vencelam8287 2 роки тому +2

      @@TonoNamnum The proper way to create & initialize a map: 1. m := make(map[int]int), 2. m := map[int]int{}

    • @jeffreysmith9837
      @jeffreysmith9837 7 місяців тому

      ​​@@vencelam8287you can initialize nil maps created with new()
      *nMap = make(map[int]int)
      *nMap = map[int]int{}
      both work

  • @tiagoernst5167
    @tiagoernst5167 2 роки тому +9

    Would'we been interesting to say in which scenario new or make are a better fit

  • @ayushdedhia25
    @ayushdedhia25 2 роки тому +5

    Now that's what the concept i was confused 😅 thanks to clear it 👍🏻

  • @gerardgauthier4876
    @gerardgauthier4876 2 роки тому +4

    As always, full marks on presentation. Nice font size and good contrast for your editor/terminal shots.

  • @blackswan2020
    @blackswan2020 Рік тому

    This is by far the best channel for learning Go 🙏🏻 thank you!!

  • @neerajbg
    @neerajbg 2 роки тому +2

    I think new is very useful for instantiating an object of a struct, form struct. while make is a failsafe kind.

  • @esra_erimez
    @esra_erimez 2 роки тому +1

    2:02 Not to split hairs, but new returns a reference that is stored in a pointer variable.

  • @grrrlag
    @grrrlag 2 роки тому +2

    I'm trying to remember if new is actually required for anything. for structs you can just `&MyStruct{}` instead.

    • @cookie_of_nine
      @cookie_of_nine 2 роки тому

      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

  • @nicosummer9020
    @nicosummer9020 2 роки тому +2

    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 🤭

    • @sweetphilly2
      @sweetphilly2 Рік тому

      Junmin Lee has a great playlist for data structures in Go

  • @raf6125
    @raf6125 Рік тому

    Awesome video!

  • @ekallivrousis
    @ekallivrousis 2 роки тому

    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.

  • @whatthefunction9140
    @whatthefunction9140 2 роки тому +2

    Love your accent. Wish I knew Japanese.

  • @matsonkepson8381
    @matsonkepson8381 2 роки тому

    still dont get it , why to use new() if its returning nil though ?

  • @TaMaGaFtPlayer
    @TaMaGaFtPlayer 2 роки тому +1

    then, why should people use "new()"?(like in map example)

    • @TonoNamnum
      @TonoNamnum 2 роки тому +2

      if you want a variable to be allocated on the heap in order to persist for example

    • @cookie_of_nine
      @cookie_of_nine 2 роки тому +1

      @@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.

  • @vinaykumarva8538
    @vinaykumarva8538 2 роки тому +1

    I'm waiting for your video I want more basic go Lang.....

  • @sarthaktiwari8515
    @sarthaktiwari8515 2 роки тому

    Let's goo

  • @mattgarelli1371
    @mattgarelli1371 2 роки тому

    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.