Skip to content

How to move out value from Result like Rust? #20

@theSprog

Description

@theSprog

Hi, I'm using this Result type and wondering what's the idiomatic way to move out the contained value?

For example, with a Result containing a movable type like mystring(class impl by myself):

#include "result.hpp"

class MyString {
    std::string data;
public:
    MyString() : data() {
        std::cout << "Default constructor\n";
    }
    
    MyString(const char* s) : data(s) {
        std::cout << "Constructor from const char*\n";
    }
    
    // delete copy for some reason
    MyString(const MyString& other) = delete;
    MyString& operator=(const MyString& other) = delete;
    
    MyString(MyString&& other) noexcept : data(std::move(other.data)) {
        std::cout << "Move constructor\n";
    }
    
    MyString& operator=(MyString&& other) noexcept {
        std::cout << "Move assignment\n";
        if (this != &other) {
            data = std::move(other.data);
        }
        return *this;
    }
    
    ~MyString() {
        std::cout << "Destructor\n";
    }
};

Result<MyString, int> get_mystring() {
    return Ok(MyString("hello"));
}

int main() {
    MyString s1 = get_mystring().unwrap();
}

// How to move the string out without copying?
mystring s = get_string().unwrap(); // This seems to make a copy

I see the current unwrap() implementation returns by value and is const, which forces a copy. Is there an existing way to move out the value that I'm missing?
If there isn't one currently, would you add an rvalue-reference unwrap()?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions