Hi,
Trying to build simple api with actix but getting error "can not infer type". How can i solve this by specifying trait in generic function?
Specifying state in actix data like :
app.service(
web::scope("/app")
.data(state())
.service(index)
)
Index Function (not working)
#[get("/index")]
async fn index<S>(state: web::Data<S>) -> impl Responder
where S: 'static + AppStateTrait
{
HttpResponse::Ok().json(Response { result: true, index: state.data() })
}
Full Code:
use actix_web::{App, HttpServer, web, Responder, HttpResponse, get, post};
use log::info;
use serde::{Serialize, Deserialize};
use std::sync::Arc;
use std::cell::Cell;
use std::ops::Deref;
use std::collections::HashMap;
extern crate simple_logger;
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
simple_logger::init_with_level(log::Level::Info).unwrap();
start_server().await
}
async fn start_server() -> std::io::Result<()>
{
HttpServer::new(move || {
let mut app = App::new();
app.service(
web::scope("/app")
.data(state())
.service(index)
)
})
.workers(2)
.keep_alive(15)
.bind("127.0.0.1:8088")?
.run()
.await
}
fn state() -> impl AppStateTrait {
AppState {
index: 2
}
}
// =========== NOT WORKING ========
#[get("/index")]
async fn index<S>(state: web::Data<S>) -> impl Responder
where S: 'static + AppStateTrait
{
HttpResponse::Ok().json(Response { result: true, index: state.data() })
}
// ======== WORKING ============
/*#[get("/index")]
async fn index(state: web::Data<AppState>) -> impl Responder
{
HttpResponse::Ok().json(Response { result: true, index: state.data() })
}*/
trait AppStateTrait {
fn data(&self) -> u32;
}
struct AppState {
index: u32,
}
impl AppStateTrait for AppState {
fn data(&self) -> u32 {
self.index
}
}
#[derive(Deserialize)]
pub struct Request {
commands: String,
}
#[derive(Serialize)]
pub struct Response {
result: bool,
index: u32,
}