DEV Community

Selfish Dev
Selfish Dev

Posted on

Variables and GO!

Introduction

A variable is a container that holds a value, which can change over time.

In Go, there are two types of variables:

Constant and Variable

const gravity float32 = 9.8 // Immutable Variable
var age int = 23 // Mutable Variable
Enter fullscreen mode Exit fullscreen mode

The value of a constant (const) cannot be changed. This will result in an error.

The value of a variable (var) can be changed multiple times throughout the program.

CONST are mostly used in cases where you don't want to mistakenly change the value somewhere

How to declare them

There are 3 ways to declare a variable in GO

Method 1

var name string = "Selfish Dev" 
Enter fullscreen mode Exit fullscreen mode

Since Go is a strongly and statically typed language, you are required to define the type of a variable every time you create one. However , There are ways to get away from defining this using Method 2 and 3 but defining types is considered a good practice in programming because:

  • It makes your code more readable.
  • It helps catch errors early.
  • It prevents unexpected behavior by ensuring type safety.

Method 2

var name = "Selfish Dev"
Enter fullscreen mode Exit fullscreen mode

Using this method, Go automatically determines the data type of name. Since "Selfish Dev" is a string, Go assigns name the string type."

Method 3

name := "Selfish Dev"
Enter fullscreen mode Exit fullscreen mode

This is the simplest way to declare a variable in Go. The := operator assigns the string "Selfish Dev" to the variable.

Things to avoid

To write clean and error-free Go code, follow these best practices:

  • Avoid using special Characters in variable names
  • Avoid starting variable name with a digits
  • Avoid using keywords as variable name

Examples
#price - Has special Chracter
@age - Has special Chracter
1Name - Starts with a digit
14th_Player - Starting with Digit
if - Registered GO keyword
else - Registered GO keyword

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay