blockchainmove-langsuiaptos

Checking if a parameter is a literal string in sui move


I want to check if a field: string::String in a struct is the exact string.

struct A has key, store {
    id: UID,
    field: string::String,
}

public entry fun is_field_hello(a: &A): bool {
    a.field == 'hello'
}

This is the compiler error I got:

error[E01001]: invalid character
   ┌─ .\sources\identities.move:89:20
   │
89 │         a.field == 'hello'
   │                    ^ Invalid character: '''

Failed to build Move modules: "Compilation error".

How can I enter a string into my codes?

Or alternatively, I can make comparison between vectors but the question then becomes how do I enter a literal vector into my codes?


Solution

  • You should be able to do the following:

    public entry fun is_field_hello(a: &A): bool {
        a.field == std::string::utf8(b"hello")
    }
    

    b"hello" is shorthand for a vec<u8>[...], containing the string, and then std::string::utf8 takes in a vec<u8> and returns a string (without checking for valid UTF8)