<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: BhanuReddy</title>
    <description>The latest articles on Forem by BhanuReddy (@bhanu011).</description>
    <link>https://forem.com/bhanu011</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F213611%2Fa3d01d07-5b67-499c-b5b1-a311532805f6.jpeg</url>
      <title>Forem: BhanuReddy</title>
      <link>https://forem.com/bhanu011</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bhanu011"/>
    <language>en</language>
    <item>
      <title>How is new() different in Go?</title>
      <dc:creator>BhanuReddy</dc:creator>
      <pubDate>Sun, 21 Nov 2021 03:45:13 +0000</pubDate>
      <link>https://forem.com/bhanu011/how-is-new-different-in-go-41lk</link>
      <guid>https://forem.com/bhanu011/how-is-new-different-in-go-41lk</guid>
      <description>&lt;h2&gt;
  
  
  what is new()?
&lt;/h2&gt;

&lt;p&gt;new() is a builtin function, used to create zero values(doesn't initializes memory) and returns pointer. new() can be used to declare any data type. In other words it returns a pointer to a newly allocated zero value of type T. &lt;/p&gt;

&lt;h2&gt;
  
  
  what is make()?
&lt;/h2&gt;

&lt;p&gt;make() is a builtin function, used to create non zero value and it does not return pointer. It is used to create only map, slice and channels data types. Using make() we can also define length, capacity for slice, initial capacity for map and buffer length for channels.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1y5k7jkv88ij2x6vvspd.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1y5k7jkv88ij2x6vvspd.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Can we create map, slices and channels with new function?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;what is the distinction with these 3 data types? Because these three data types under the covers refers to data structures which has to be initialized before use. For maps, slices and channels make initializes the internal data structure and prepares the value.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can create zero valued types, but even without using new() function same functionality can be achieved below are the examples&lt;/p&gt;

&lt;p&gt;new(map) is similar to &lt;code&gt;var m map[string]int&lt;/code&gt; and returning pointer to m. Here is the example since map behaves like empty while reading and nil during writing we see errors when write to a map happens before allocating memory.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://play.golang.org/p/AvIndq1Q7L8" rel="noopener noreferrer"&gt;creating map reference using new function&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;new(slice) creates a slice with zero value and returns pointer. In below example, append function checks size and capacity of slice and manages backing array before appending value. see the example below it looks like new() has initialized memory but that is actually done by append()&lt;/p&gt;

&lt;p&gt;&lt;a href="https://play.golang.org/p/IxfmM7WSR1x" rel="noopener noreferrer"&gt;creating slices using new function&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;new(chan type) creates a channel with zero value that is a nil channel. Try running below example to see what happens when a value is sent to channel created with new() function.&lt;br&gt;
Expect some errors!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://play.golang.org/p/Gx2fBYURPXQ" rel="noopener noreferrer"&gt;create channel with new function&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the specific problem new is trying to solve?
&lt;/h2&gt;

&lt;p&gt;What ever new() function is doing can be achieved by initializing a data type and getting a pointer that data type. In below example both n and n1 looks same and n1 is much more readable and highlights that it is pointer&lt;/p&gt;

&lt;p&gt;`&lt;br&gt;
type Name struct {&lt;br&gt;
    FirstName string&lt;br&gt;
    LastNamae string&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;func main() {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;n := new(Name)
n1 := &amp;amp;Name{}

fmt.Printf("Name: %v \n Name1: %v", n, n1)  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
`&lt;/p&gt;

&lt;p&gt;new() in golang is different to new() in other programming languages always remember that new() in Go doesn't initialize memory but it only zeroes the value and return the pointer. To understand this better let us look at below example&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;br&gt;
var x *int&lt;br&gt;
y := new(int)&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
What is the difference in above statements? first statement states that x can hold a pointer to integer data type. Second statement tells that zeroed value for int is set and pointer to that is returned. Run below example to understand&lt;/p&gt;

&lt;p&gt;&lt;a href="https://play.golang.org/p/kBHZtRF4qB3" rel="noopener noreferrer"&gt;How is new() different? Playground Link&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;new() is different to make() and even without using new() zero valued initialization can be done. May be it is idiomatic way to use new() but other wise I don't see any specific use case which new() is solving. If you see any use case where only new() is able to solve please drop it in comments. Let me know what you think about the post.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://groups.google.com/g/golang-nuts/c/kWXYU95XN04" rel="noopener noreferrer"&gt;discussion on new and make can be merged into one&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;span&gt;Checkout my other article &lt;a href="https://dev.to/bhanu011/map-types-in-go-3h2i"&gt;maps in Go&lt;/a&gt;&lt;/span&gt;&lt;/p&gt;

</description>
      <category>go</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Map types in GO</title>
      <dc:creator>BhanuReddy</dc:creator>
      <pubDate>Sun, 07 Nov 2021 15:40:40 +0000</pubDate>
      <link>https://forem.com/bhanu011/map-types-in-go-3h2i</link>
      <guid>https://forem.com/bhanu011/map-types-in-go-3h2i</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhbuw0qcneohvve67ottc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhbuw0qcneohvve67ottc.png" alt="Maps in GO"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A map is an unordered collection of key/value pairs, where each key is unique. If you are coming from python this is similar to dictionary.&lt;/li&gt;
&lt;li&gt;Go provides a built in map type that implements hash table and stores key/value pairs into buckets&lt;/li&gt;
&lt;li&gt;Hash tables provide fast lookup, addition and deletion.&lt;/li&gt;
&lt;li&gt;The idea behind hash map is to have O(1) lookup time on average. Generally it is O(n) provided if hash function gives n collisions which is very rare in real time&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets see the basic operations of map in golang.&lt;/p&gt;

&lt;h2&gt;
  
  
  Declaration
&lt;/h2&gt;

&lt;p&gt;Below declaration implies that m is a Map with key as string and value as int&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

var m map[string]int


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Initialization
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The make() function is a built-in function in go which is used to initialize maps along with slices and channels.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Note that make() function creates generic values for map, slices and channels and it never returns pointer.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Map m1 initializes map with string as key and int as value. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 m1 := make(map[string]int)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Map m2 is initialized with string as key, int as value and with a capacity of 10 elements which means that it is only a hint that an initial capacity can be 10 (space for initial 10 elements before reallocation happens) but it won't restrict if elements are more than mentioned initial capacity.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;capacity is hint for total number of key/value pairs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 m2 := make(map[string]int, 10)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The default number of buckets is 1. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Each bucket is an array with array of 8 elements. Once number of entries in each bucket reaches an average load of buckets, the map get bigger by doubling its number of buckets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Map m3 is initialized with string as key, int as value storing "RED", "BLUE" as keys and 1, 2 as values respectively&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 var m3 := map[string]int {
    "RED": 1,
    "BLUE": 2,
  }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc2k5n9bira4gwik2zvm8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc2k5n9bira4gwik2zvm8.png" alt="Maps in Go"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Zero value of map
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;If map is declared and initialization is not done then map acts like empty map while reading and map acts like nil while writing, keep this in mind when you are declaring a map next time.
```
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;func main() {&lt;br&gt;
    var m map[string]int //Declaration&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//READING VALUE FROM MAP
v := m["key"]

fmt.Printf("Read value from map %+v \n", v)

//WRITING VALUE TO MAP
m["key2"] = 973

fmt.Printf("values in map %+v \n", m)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
from above example reading happens without any issue since map is behaving like empty map while reading, but at line where we are trying to assign value to map `m["key2"] = 973` compiler panics with message "assignment to entry in nil map".

[Try above example in playground] (https://play.golang.org/p/lZTRB2b6o3i)

## MAP OPERATIONS

### Insert/Update
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;m := make(map[string]int)&lt;br&gt;
m["RED"] = 123&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add to map with key "RED" and value as 123.
### Delete
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;delete(m, "BLUE")&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;delete elements with key values as BLUE

### Iterate over all elements in map

Keyword range can be used to iterate over all elements
in map as you can see in below sample code when range is used it returns key, value pair.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;m := map[string]int {&lt;br&gt;
    "RED": 1,&lt;br&gt;
    "BLUE": 2,&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;for key, val := range m {&lt;br&gt;
    fmt.Printf("key: %s, value: %d", key, val)&lt;br&gt;
}&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
### Get Values from Map
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;val := m["RED"]&lt;br&gt;
val, ok := m["BLUE"]&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while getting values from map it returns two variables,value and bool. Bool indicates whether the key exists in map.

### What is the use of returned bool value?

- Note that value returned from map will be zero value if key is not present, for example if int is the value for string key but given key is not available in map then zero is returned(since zero value of int is zero). 
- This helps in understanding whether value is present as zero for the given key or since key is not available in map zero is returned.

### What data types can be used as key in Map?

Any data type which has equality operation defined can be used as key in map that is == and != should be defined on those data types going by that logic we can't have below data types as keys in map
    &amp;amp;emsp;* slice 
    &amp;amp;emsp;* functions
    &amp;amp;emsp;* map

## Concurrency

- Maps are not safe for concurrent use: it’s not defined what happens when you read and write to them simultaneously. 
- If you need to read from and write to a map concurrently, the accesses must be controlled by some kind of synchronization mechanism. 
- One common way to protect maps is with sync.RWMutex.

Below statement declares struct stats with RWMutex and a map with string as key and int ass value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;var counter = struct{&lt;br&gt;
    sync.RWMutex&lt;br&gt;
    m map[string]int&lt;br&gt;
}{m: make(map[string]int)}&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Reading from stats using Read Lock(concurrent safe read)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;counter.RLock()&lt;br&gt;
n := counter.m["total_requests"]&lt;br&gt;
counter.RUnlock()&lt;br&gt;
fmt.Println("total_requests:", n)&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Writing to stats using Write Lock(concurrent safe write)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;counter.Lock()&lt;br&gt;
counter.m["some_key"]++&lt;br&gt;
counter.Unlock()&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
## What does a Map variable hold?

- Maps are not reference variables. 
- Go also doesn't have pass by reference since it doesn't have reference variables. 
- To understand more on what is reference variable read below post from Dave Cheyney.

[There is no pass by reference in go] (https://dave.cheney.net/2017/04/29/there-is-no-pass-by-reference-in-go)

- Map m is actually a pointer to 'runtime.hmap'. 
- To confirm the same run below code in go playground and see that both map variable m and uintptr has same size

[compare map variable with uintptr in go playground] (https://play.golang.org/p/_LzTPX14PsB)

Access hmap and maptype struct which a map is pointed to, run below code in playground to see hmap struct. Try changing key data type, capacity of map etc to see how hmap and maptypes vary.

[observe hmap and maptype structs]
(https://play.golang.org/p/Do3kM1B4WHg)

## Compile Time

Go compiler rewrites map operations with different functions calls in runtime below are function calls for respective map operations

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;m := make(map[int]int)  → runtime.makemap(&amp;amp;t, 0, &amp;amp;h, &amp;amp;b)&lt;br&gt;
v := m["RED"]     → runtime.mapaccess1(m, ”RED", &amp;amp;v)&lt;br&gt;
v, ok := m["BLUE"] → runtime.mapaccess2(m, ”BLUE”, &amp;amp;v, &amp;amp;ok)&lt;br&gt;
m["CYAN"] = 143   → runtime.mapinsert(m, ”CYAN", 143)&lt;br&gt;
delete(m, "BLUE")  → runtime.mapdelete(m, “BLUE”)&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;##Conclusion
I hope this will be useful as a reference for Maps. I will try to add more details on sync.Map in a separate post. If there is something which can be improved/not clear in above post please let me know in comments.
## References
[Dave Cheyney's talk on How Maps are implemented in go] 
(https://www.youtube.com/watch?v=IQ3esT7AgBs)
[Discussion on Why maps are not as *map since it is pointer] (https://groups.google.com/g/golang-nuts/c/SjuhSYDITm4)

EDIT 1 : updated variable stats to counter under concurrency as suggested by @dogers 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>go</category>
      <category>map</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
