Golang Tips & Tricks #5 - blank identifier in structs

While working with structures, there’s a possibility to initialize the structure without providing the keys of fields.

type SomeSturct struct {
  FirstField string
  SecondField bool
}

// ...

myStruct := SomeSturct{"", false}

If we want to force other (or even ourselfs) to explicitly providing the keys, we can add _ struct{} in the end of the structure.

type SomeSturct struct {
  FirstField string
  SecondField bool
  _ struct{}
}

// COMPILATION ERROR
myStruct := SomeSturct{"", false}

The code above will produce too few values in SomeSturct literal error. Try it yourself.

In Go, the blank identifier in the type has size 0 and it means “blank identifier.” Because it’s black, it cannot be accessed directly. It forces us to use the fields’ names explicitly. This technique can be used to avoid bugs that might arise from specifying the arguments in an incorrect order.

golang   tipstricks
Published in: Golang
Did you like the post?
or

About the author

Hi! My name is Bartek. I'm a developer since 2011. I love to learn by sharing the knowledge. You can find me on Twitter or Linkedin. I'm a backend engineer at Brainly.

Recent posts

I want to help you become a developer

That's why I can let you know about new blogposts on your email

You can find me

You May Also Enjoy

Golang Tips & Tricks #6 - the _test package 14 Aug 2019

Testing is one of the hardest stuff in programming. Today trick will help you organize your tests and the production code. Let's assume you have a package called `orders`. When you want to separat...
golang   tipstricks   tests
read more...

Golang Tips & Tricks #4 - internal folders 25 Mar 2019

While developing a library, we create a directory structure to keep the code organized. However, some exported functions or struct should not be used by users of the library. The achieve that, call...
golang   tipstricks
read more...

Golang Tips & Tricks #3 - graceful shutdown 18 Mar 2019

In the microservices’ world, one thing what’s worth considering is a graceful shutdown. This is important to not lose data while shutting down a container. The container orchestrator like Kubernete...
golang   tipstricks
read more...