Idiomatic scan of empty field

Is there an idiomatic way to scan a string that has an empty field?

Specifically…

This tiny example works fine: [https://play.golang.org/p/VrQtKqtorFi]

But if target has an empty field like this (notice the leading field is now empty):

target := ";1;1551121142780;303421;26.70921316;true"

then I get

panic: strconv.ParseFloat: parsing "": invalid syntax

because strconv cannot parse an empty string.

Should I create my own “Float” object with a .Scan method, or is there some more straightforward way?

Thanks!

It seems that Scanf is the problem.
This works fine :
s, _:= strconv.ParseFloat("", 32)
fmt.Println(s)

Thanks, Yamil, but in your example, ParseFloat is actually throwing the same error. Your code just did not check the error so the zero value returned looked correct: Here is the error

[https://play.golang.org/p/uX5TkApsQs1]

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s, err := strconv.ParseFloat("", 32)
	fmt.Println(s, err)

}

You could do like this: https://goplay.space/#cG7oZD_co3C A little bit more too write. But you can ignore the errors from the strconv functions if you are ok with the default values (0 and 0.0)

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	target := ";1;155142780;303421;26.70921316;true"

	fields := strings.Split(target, ";")

	scale, _ := strconv.ParseFloat(fields[0], 32)
	size, _ := strconv.ParseInt(fields[1], 0, 64)
	stamp, _ := strconv.ParseInt(fields[2], 0, 64)
	count, _ := strconv.ParseInt(fields[3], 0, 64)

	fmt.Printf("Scale:%f Size:%d Stamp:%d Count:%d\n", scale, size, stamp, count)

}

Thanks, Johan. I think that is the right solution.

W

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.