rust dyn trait variable new with different generic types?

Viewed 85

I'm quite new to Rust. Trying to create database connection with diesel-rs.

Here's part of my code:

use diesel::Connecction;
use diesel::mysql::MysqlConnection;
use diesel::sqlite::SqliteConnection;

let engine = "mysql";
let mysql_url = "mysql://username:password@localhost:3306/test";
let sqlite_url = "sqlite://sqlite.db";
let connection : Box<dyn Connection> = if engine == "mysql" {
  Box::new(MysqlConnection::establish(mysql_url).unwrap())
} else {
  Box::new(SqliteConnection::establish(sqlite_url).unwrap())
}

Here's the compiler error:

error[E0191]: the value of the associated types `Backend` (from trait `Connection`), `TransactionManager` (from trait `Connection`) must be specified
  --> src/quant/common/persistence/database.rs:11:25
   |
11 |     connection: Box<dyn Connection>,
   |                         ^^^^^^^^^^ help: specify the associated types: `Connection<Backend = Type, TransactionManager = Type>`

Is it possible to create different connection when program starts with different parameters ?

1 Answers

This use case is not supported. See this issue. If you manage to do this with connection, you'll have to wrap the transaction and queries, and then likely some of the generated table! types, and down to a rabbit hole.

Related