* float32和int值相乘

I have 2 fields that I have to multiply. One is a *float32 field and another is an int field. How can I multiply these fields?

var totalPrice *float32
var price *float32
var volume int

this code doesn't work. I get the error ... mismatched types *float32 ...

totalPrice = price * volume

You need to convert using type conversion as is explained quickly here. In this case as mkopriva highlight in his comment, you should convert volume variable's value to a float32.

Also allow to show a way to deal with nil values that has a meaning in the application level, for that i wrote the float32PtrToFloat(*float32,float32) with the second parameter that allows you to specify what value shall be taken instead of nil.

Assuming that a nil value translates to zero value, here goes the complete example

package main

import (
    "fmt"
)

func main() {
    var totalPrice *float32
    var price *float32
    var volume int

    var total = float32PtrToFloat(price, 0) * float32(volume)
    totalPrice = &total
    fmt.Println(*totalPrice)

}

func float32PtrToFloat(price *float32, valueIfNil float32) float32 {
    if price == nil {
        return valueIfNil
    } else {
        return *price
    }
}

And a personal reading, following JimB advice, try to not use floats for currency values as floating point arithmetic is not reliable. Instead use integer values, using the 1 as the lower value in the current currency, for example:

  • 1 = 1 penny (or)
  • 1 = 1 cent (or)
  • 1 = 1 centavo (in my case)