Reputation: 2797
Want to have an empty char/byte, which has zero size/length, in Go, such as byte("")
.
func main() {
var a byte = '' // not working
var a byte = 0 // not working
}
A more specific example is
func removeOuterParentheses(S string) string {
var stack []int
var res []byte
for i, b := range []byte(S) {
if b == '(' {
stack = append(stack, i)
} else {
if len(stack) == 1 {
res[stack[0]] = '' // set this byte to be empty
res[i] = '' // / set this byte to be empty
}
stack = stack[:len(stack)-1]
}
}
return string(res)
}
There is an equivalent question in Java
Upvotes: 2
Views: 19656
Reputation: 9
a single byte is a number. 0 would transform into a 8bit number. 00000000.
A byte slice/array can have a length of 0.
var a byte = 0
var b = [0]byte{}
Upvotes: 1
Reputation: 27822
A byte
is an alias to the uint8
type. Having an "empty byte" doesn't really make any sense, just as having an "empty number" doesn't make any sense (you can have the number 0, but what is an "empty" number?)
You can assign a value of zero (b := byte(0)
, or var b byte
), which can be used to indicate that nothing is assigned yet ("zero value"). The byte value of 0
is is known as a "null byte". It normally never occurs in regular text, but often occurs in binary data (e.g. images, compressed files, etc.)
This is different from byte("")
, which is a sequence of bytes. You can have a sequence of zero bytes. To give an analogy: I can have a wallet with no money in it, but I can't have a coin that is worth "empty".
If you really want to distinguish between "value of 0" and "never set" you can use either a pointer or a struct. An example with a pointer:
var b *byte
fmt.Println(b) // <nil>, since it's a pointer which has no address to point to.
one := byte(0)
b = &one // Set address to one.
fmt.Println(b, *b) // 0xc000014178 0 (first value will be different, as it's
// a memory address).
You'll need to be a little bit careful here, as *b
will be a panic if you haven't assigned a value yet. Depending on how it's used it can either work quite well, or be very awkward to work with. An example where this is used in the standard library is the flag
package.
Another possibility is to use a struct with separate fiels for the byte itself and a flag to record whether it's been set or not. In the database/sql
library there are already the Null*
types (e.g. NullInt64
, which you can use as a starting point.
Upvotes: 4