---
title: get_or_set_with
summary: Get the entry associated with the given cache key if it exists, or insert and return an entry specified by running the given closure.
url: https://www.fastly.com/documentation/reference/compute/sdks/rust/fastly/cache/simple/fn.get_or_set_with/
---

**Kind:** Function  
**Module:** [simple](https://www.fastly.com/documentation/reference/compute/sdks/rust/fastly/cache/simple/)  
**Package:** fastly 0.13.1  
**Source:** https://docs.rs/crate/fastly/0.13.1/source/src/cache/simple.rs#184

```rust
fn get_or_set_with<F>(key: impl Into<CacheKey>, make_entry: F) -> Result<Option<Body>, CacheError>
where
    F: FnOnce() -> Result<CacheEntry, Error>,
```

Get the entry associated with the given cache key if it exists, or insert and return an entry
specified by running the given closure.

The closure is only run when no value is present for the key, and no other client is in the
process of setting it. It takes no arguments, and returns either `Ok` with a [`CacheEntry`](https://www.fastly.com/documentation/reference/compute/sdks/rust/fastly/cache/simple/struct.CacheEntry/)
describing the entry to set, or `Err` with an [`anyhow::Error`](https://docs.rs/anyhow/1.0.100/anyhow/struct.Error.html). The error is not interpreted by
the API, and is solely provided as a user convenience. You can return an error for any reason,
and no value will be cached.

#### Argument type conversion

See the `From` impls for [`Bytes`](https://docs.rs/bytes/latest/bytes/bytes/struct.Bytes.html) to see which types can be used
as a key.

##### Example successful insertion

```rust
let value = get_or_set_with("my_key", || {
    Ok(CacheEntry {
        value: "hello!".into(),
        ttl: Duration::from_secs(60),
    })
})?
.expect("closure always returns `Ok`, so we have a value");
let cached_string = value.into_string();
println!("the cached string was: {cached_string}");
```

##### Example unsuccessful insertion

```rust
let mut tried_to_set = false;
let result = get_or_set_with("my_key", || {
    tried_to_set = true;
    anyhow::bail!("I changed my mind!")
});
if tried_to_set {
    // if our closure was run, we can observe its error in the result
    assert!(matches!(result, Err(CacheError::GetOrSet(_))));
}
```

**Parameters**

- `key`: `impl Into<CacheKey>`
- `make_entry`: `F`

**Returns**

`Result<Option<crate::Body>, CacheError>`
