Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can't implement trait (e.g., Clone) for recursive datatype that uses Option #1346

Open
tjhance opened this issue Nov 14, 2024 · 1 comment
Open

Comments

@tjhance
Copy link
Collaborator

tjhance commented Nov 14, 2024

Suppose you want to implement Clone for a recursive datatype:

struct Node {
    child: Option<Box<Node>>,
}

impl Clone for Node {
    fn clone(&self) -> Self {
        Node {
            child: self.child.clone()
        }
    }
}

This currently gives a "cyclic self-reference" error.

It should theoretically be possible to prove termination here. And it should be optional, anyway (since it's exec code).

@tjhance tjhance changed the title can't implement trait (e.g., Clone) for recursive datatype can't implement trait (e.g., Clone) for recursive datatype that uses Option Nov 14, 2024
@tjhance
Copy link
Collaborator Author

tjhance commented Nov 14, 2024

the presence of Option is the part that trips it up. If you inline the Option-handling instead of relying on Option::clone it works fine:

struct Node {
    child: Option<Box<Node>>,
}

impl Clone for Node {
    fn clone(&self) -> Self {
        Node {
            child: match &self.child {
                Some(node) => Some(Box::new((&**node).clone())),
                None => None,
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant