Int and binary.write, distraction, confusion

Hi,

I’m thinking I do things the wrong way.

As I understand the size of int is not defined and Go seems to copy what C did? Anyways, so the size of the type of len(x) is not defined, or at least not defined enough for binary.Write not to complain.

So, the right way to handle this is using an int64 instead? That is, if I want to write to a file what len(x) returns, I should just use a temporary variable and a bit more code, right? It’s ugly.

I don’t like to use json, don’t want be dependent on language runtimes or lots of code that parses json for me.

Is there a nicer way to serialize data into buffers or files that does not use an int64 for an int? (not with the golang typeparams branch?)

N/o/n-w/o/r/k/i/n/g Working code that tries to fix it for me:

Edit: Whoops, it does work. I was just to nitpicky and didn’t want to go on and remove a typo somewhere else. Sorry.

func save_var(file *os.File, x interface{}) {

	switch t := x.(type) {

		case int:
		x = int64(x.(int))
		_ = t

		case custom_type_t:
		x = int64(x.(custom_type_t))
		_ = t
	}

	err := binary.Write(file, binary.LittleEndian, x)
	if err != nil { panic(err) }
}

Even prettier:

func load_var(file *os.File, x interface{}) {

	switch t := x.(type) {

		case *int:
		x = (*int64)(unsafe.Pointer((x.(*int))))
		_ = t

		case *custom_type_t:
		x = (*int64)(unsafe.Pointer((x.(*custom_type_t))))
		_ = t
	}

	err := binary.Read(file, binary.LittleEndian, x)
	if err != nil { panic(err) }
}

I would use an int64 everywhere if they were compatible with len(), but I’m about as confused as in C++ deciding/defaulting for int and then hitting size_t in the STL containers. :upside_down_face:

Thanks for reading.

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