243 words
1 minutes
StringView

link#

C vs Rust pointer comparison#

ConceptCRust
pointer to structString_View *&mut StringView
arrowsv->countsv.count
address&s&mut s
modifypointermutable reference
pointer mathallowednot allowed
slicingmanualbuilt-in

C code#

// main.c
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    const char *data;
    size_t count;
} String_View;

// Hello, World0...
// ^          ^

String_View sv(const char *cstr) {
    return (String_View){
        .data = cstr,
        .count = strlen(cstr),
    };
}

void sv_chop_left(String_View *sv, size_t n) {
    if (n > sv->count)
        n = sv->count;
    sv->count -= n;
    sv->data += n;
}

void sv_chop_right(String_View *sv, size_t n) {
    if (n > sv->count)
        n = sv->count;
    sv->count -= n;
}

int main() {
    String_View s = sv("Hello, World");
    sv_chop_right(&s, 3);
    sv_chop_left(&s, 2);
    printf("%.*s\n", (int)s.count, s.data);

    return 0;
}

Rust code#

// main.rs
#[derive(Debug, Clone, Copy)]
struct StringView<'a> {
    data: &'a str,
    count: usize,
}

impl<'a> StringView<'a> {
    fn sv(s: &'a str) -> Self {
        Self {
            data: s,
            count: s.len(),
        }
    }

    fn sv_chop_left(sv: &mut Self, n: usize) {
        let n = n.min(sv.count);

        sv.data = &sv.data[n..];
        sv.count -= n;
    }

    fn sv_chop_right(sv: &mut Self, n: usize) {
        let n = n.min(sv.count);

        sv.count -= n;
        sv.data = &sv.data[..sv.count];
    }
}

fn main() {
    let mut s = StringView::sv("Hello, World");

    StringView::sv_chop_right(&mut s, 3);
    StringView::sv_chop_left(&mut s, 2);

    println!("{}", s.data);
}
  • Result
llo, Wo
StringView
https://younghakim7.github.io/blog/posts/stringview/
Author
YoungHa
Published at
2026-03-20