RUST : How to check null value in rust

1 minute read

How to check null value in rust

A question arose When i linking C language with rust language. That’s how to check null value in rust? Rust has Option<T> instead of null. because problem with null values is that if you try to use a null value as a not-null value. So Rust made new type Option<T> to prevent error. If you get a more infomation click here!!

Anyway I will try to new type. almost pointer has null value. I will replace the sample code written in C with rust.

// C language
int *ptr = NULL;
if (ptr == NULL) { 
  return; 
}

How to change to rust? Let’s look at the code first and analyze it.

// rust language
let ptr: Option<*const i32> = None;
if let None = ptr {
  return;
}

What has changed?

  • Options<T> type.
  • NULL value to None
  • if let statment

In brief, Options<T> type is enum. That has Some(T) and None. Some(T) means value is present, None means has nothing. If you want to know more, find it yourself.

I thought I was scared of ‘new type’ or ‘not exist about null’. It was really difficult at first because there was no null. But it was changed so easily. Now that you know it, take it well and let’s master the rust language !!


reference)