Significance of Go — Part 3 (Variables, Pointer Arithmetic and Constants/iota)

Variable Declaration

No Pointer Arithmetic

package mainimport (
"fmt"
)
func main() {
var m *int = new(int)
*m = 100 fmt.Println(*m)
}
Pointers in Go
package mainimport (
"fmt"
)
func main() {
var m *int = new(int)
*m = 100 fmt.Println(*(m + 1))
}
Pointer Arithmetic fails in Go

No Implicit Type Conversions

package mainimport (
"fmt"
)
func main() {
var i = 100
var j = 3.14

fmt.Println(i + 1)
fmt.Println(j + 1.3)
}
Supports implicitly typed constants
  • In line 11, it decides that i is an integer and adds 1 to it
  • In line 12, it decides that i is a float and adds 1.3 to it
package mainimport (
"fmt"
)
func main() {
var i int = 100
var j float32 = 3.14

fmt.Println(i + j)

}
Gives an error
package mainimport (
"fmt"
)
func main() {
var i int = 100
var j float32 = 3.14

fmt.Println(float32(i) + j)
}
Successful explicit type casting

iota

package mainimport (
"fmt"
)
func main() {
const (
zero = iota
one = iota
)
fmt.Println(zero, one)
}
iota example
package mainimport (
"fmt"
)
func main() {
const (
zero = iota
one
)
fmt.Println(zero, one)
}
package mainimport (
"fmt"
)
func main() {
const (
one = iota + 1
_
three
)
fmt.Println(one, three)
}
iota with underscore
  • In line 9, we have incremented the iota by 1 and assigned it to one.
  • In line 10, we use an underscore to skip the next iota value which is 2.
  • In line 11, three will get automatically assigned 3, because 2 was skipped in the previous line.
package mainimport (
"fmt"
)
func main() {
const (
one = iota
two = iota
)
const (
three = iota
)
fmt.Println(one, two, three)
}
const defined twice

Conclusion

  • There are 3 ways to declare variables in Go
  • Even Go has pointers, it does not support pointer arithmetic
  • Go does not support implicit type conversions, but we can do explicit type casting when necessary
  • Features and use cases of iota

Previous Articles

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AWS Quick Notes — Amazon API Gateway

3 Practical Tips to Make Your Java App Faster

Swift Protocol with Associated Type

Animating Projectile Motion in Python

Git and GitHub usage

Be a TechRebel: Write with us!

Speeding up Postgres Restores

First and Second Level Cache in Hibernate

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Wasura Wattearachchi

Wasura Wattearachchi

More from Medium

Review for “A View of the Parallel Computing Landscape”

461. Hamming Distance

[Rust] the function returning an empty string or None by checking "&Option<String>"

HTTP and its evolution: Diving deep into network and communication