D
D
datafilterman2020-01-10 22:13:28
go
datafilterman, 2020-01-10 22:13:28

Can you clarify the situation with typing in Go?

I started learning Golang, along the way deciding to write a generator to output dates sequentially. On the example of the standard lib time, the following script turned out

package main

import (
      "fmt"
      "time"
)

func main() {
   date := time.Date(2020,1,1,12,0,0,0,time.UTC)
   var days time.Duration = 32
   var d *time.Duration = &days
   var start time.Duration = 0
   var s *time.Duration = &start
   for *s = 0; *s < *d; *s++ {
       res := date.Add(time.Hour * 24 * *s)
       fmt.Println(res.Format("2006-01-02"))
   }
}

Guru, can you do a code review? There is a big misunderstanding of typing in Go. The time package contains a bunch of functions with custom types. I converted variables to the time.Duration type using pointers, and this option seemed suspiciously crutch to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-01-10
@datafilterman

Here is the correct option

package main

import (
  "fmt"
  "time"
)

func main() {
  date := time.Date(2020, 1, 1, 12, 0, 0, 0, time.UTC)
  var days int = 32
  var start int = 0
  for s := start; s < days; s++ {
    res := date.Add(time.Duration(s) * time.Hour * 24)
    format := res.Format("2006-01-02")
    fmt.Println(format)
  }
}

https://play.golang.org/p/Iv0DvH4OSw4
I don't understand why use a link and convert duration to duration.
Also, you do not quite understand what time.Duration is.
time.Duration is an alias of int64, but it has a different meaning, namely, it contains duration in nanoseconds.
I would also remove the declaration of types, they are redundant here, that is, variables can be declared as:
var days int = 32
var start int = 0
and
days := 32
start := 0
and in most cases, you will see the second option, but there is a BUT, namely, variables with a default value are usually not assigned a value if there is no essence and write `var start int`, (in your example it is, so it is appropriate to declare as `start := 0`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question