Skip to content

spec: Multiplication of Durations by integers makes no sense #23708

@mpnally

Description

@mpnally

I imagine this has been said many times before, but just in case ...

If I execute the following code:

package main

import (
	"fmt"
	"time"
)

func main() {
	multiplier := 10
	duration := time.Second
	product := multiplier * duration
	fmt.Printf("%v %T", product, product)
}

You would intuitively expect to see:

10s time.Duration

Instead, golang gives you

prog.go:11:24: invalid operation: multiplier * duration (mismatched types int and time.Duration)

Intuition isn't always right, but in this case I believe it is — 10s is the correct answer and Golang got it wrong. If this isn't obvious to you, ask yourself what the right answer is if I multiply 1 foot by the integer 10 — it's 10 feet. If I execute the following code:

package main

import (
	"fmt"
	"time"
)

func main() {
	multiplier := time.Duration(10)
	duration := time.Second
	product := multiplier * duration
	fmt.Printf("%v %T %v %T", product, product, multiplier, multiplier)
}

go again gives the wrong answer:

10s time.Duration 10ns time.Duration

If you multiply 10 seconds by 10 nanoseconds, the correct answer is 100 billion square nanoseconds, not 10 seconds. This is similar to multiplying 1 foot by 10 feet — the correct answer is 10 square feet. If you think a square nanosecond is a meaningless concept, then this should perhaps give an error. Other languages get duration arithmetic right — why not Go, which in most respects seems like a well thought-out language?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions