Add support to GetIntOrZero() #1276

Open
opened 2025-12-28 17:15:51 +00:00 by sami · 1 comment
Owner

Originally created by @lock9 on GitHub (Mar 21, 2024).

The following code will throw an 'Invalid Cast Exception' in runtime:

	balance := storage.Get(ctx, from).(int)
	balance += amount
	storage.Put(ctx, from, balance)

This is because it returns nil when the key is not present.

Describe the solution you'd like

I like how Neow3j solves this problem by exposing a GetIntOrZero method. As the name suggests, it will return 0 if the key is not present.

Reference:
neow3j/neow3j@f2b243a5a0/devpack/src/main/java/io/neow3j/devpack/Storage.java (L165)

Describe alternatives you've considered

I'm checking for nil before using it.

Additional context

Casting will no longer be necessary with this improvement. Another change that could help, would be to allow Get calls without the context parameter.

Don't forget to add labels!

  • component label: compiler
  • category: enhancement
Originally created by @lock9 on GitHub (Mar 21, 2024). ## Is your feature request related to a problem? Please describe. The following code will throw an 'Invalid Cast Exception' in runtime: ``` balance := storage.Get(ctx, from).(int) balance += amount storage.Put(ctx, from, balance) ``` This is because it returns `nil` when the key is not present. ## Describe the solution you'd like I like how Neow3j solves this problem by exposing a GetIntOrZero method. As the name suggests, it will return `0` if the key is not present. Reference: https://github.com/neow3j/neow3j/blob/f2b243a5a01f864a3ee9b98de52458ad534a2f88/devpack/src/main/java/io/neow3j/devpack/Storage.java#L165 ## Describe alternatives you've considered I'm checking for `nil` before using it. ## Additional context Casting will no longer be necessary with this improvement. Another change that could help, would be to allow `Get` calls without the `context` parameter. ## Don't forget to add labels! - component label: compiler - category: `enhancement`
Author
Owner

@roman-khimov commented on GitHub (Apr 1, 2024):

Related to #3381, likely can even be replaced by it.

@roman-khimov commented on GitHub (Apr 1, 2024): Related to #3381, likely can even be replaced by it.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
nspcc-dev/neo-go#1276
No description provided.