Golang: Access struct fields

Claire Lee
Aug 22, 2022

--

Either struct or struct pointer can use a dot operator to access struct fields. Go can dereference the pointer automatically. We can also parenthesize the struct point and then access fields using a dot.

Golang: access struct field summary card

Access fields of a struct

  • Use a dot operator.

Access fields of a struct pointer

  1. Use a dot operator. The pointers are automatically dereferenced.
  2. Parenthesize the struct pointer and then use a dot to access fields.

If we don’t parenthesize the struct pointer, it will show invalid indirection error. Because Go thought the field we tried to access should be a pointer.

You can access the source code here.

--

--

Claire Lee
Claire Lee

Responses (1)