error: expected initializer before 'std' and other errors after adding one line to working code - namespaces

The following program worked already before I added line 12, the line reading:
" std::cout<<" Natürlicher Logarithmus von ";std::cin>>X; ".
Now I get a lot of errors (see below)!
Please Help
// Berechnung des natürlichen Logarithmus (Grenzwert nach Hurwitz)
#include <iostream>
#include <cmath>
#include <iomanip>
double h{1.0},Result,oldResult,Limit{1.0e-8},X{2.0},Inkr;
int c{0}, prez;
int main()
std::cout<<" Natürlicher Logarithmus von ";std::cin>>X;
std::cout<<" Genauigkeit (Zehnerpotenz): ";
std::cin>>prez; prez=std::abs(prez);
Limit=std::pow(10,-prez-1);
Result=((std::pow(X,h))-1)/h;
do
{
oldResult=Result;
h=h/2.0;
Result=((std::pow(X,h))-1)/h;
Inkr=std::abs(oldResult-Result);
++c;
}
while (Inkr>Limit);
Result=std::round(Result*std::pow(10,prez))*std::pow(10,-prez);
std::cout<<std::setw(prez+3)<<std::setprecision(prez)<<std::fixed<<Result<<" \t"<<c<<'\n';
return(0);
}
Logarithmun.cpp:12:5: error: expected initializer before 'std'
12 | std::cout<<" Nat├╝rlicher Logarithmus von ";std::cin>>X;
| ^~~
Logarithmun.cpp:12:53: error: 'cin' in namespace 'std' does not name a type
12 | std::cout<<" Nat├╝rlicher Logarithmus von ";std::cin>>X;
| ^~~
In file included from Logarithmun.cpp:3:
C:/msys64/mingw64/include/c++/12.2.0/iostream:60:18: note: 'std::cin' declared here
60 | extern istream cin; /// Linked to standard input
| ^~~
Logarithmun.cpp:13:10: error: 'cout' in namespace 'std' does not name a type
13 | std::cout<<" Genauigkeit (Zehnerpotenz): ";
| ^~~~
C:/msys64/mingw64/include/c++/12.2.0/iostream:61:18: note: 'std::cout' declared here
61 | extern ostream cout; /// Linked to standard output
| ^~~~
Logarithmun.cpp:14:10: error: 'cin' in namespace 'std' does not name a type
14 | std::cin>>prez; prez=std::abs(prez);
| ^~~
C:/msys64/mingw64/include/c++/12.2.0/iostream:60:18: note: 'std::cin' declared here
60 | extern istream cin; /// Linked to standard input
| ^~~
Logarithmun.cpp:14:21: error: 'prez' does not name a type
14 | std::cin>>prez; prez=std::abs(prez);
| ^~~~
Logarithmun.cpp:15:5: error: 'Limit' does not name a type
15 | Limit=std::pow(10,-prez-1);
| ^~~~~
Logarithmun.cpp:16:5: error: 'Result' does not name a type
16 | Result=((std::pow(X,h))-1)/h;
| ^~~~~~
Logarithmun.cpp:18:5: error: expected unqualified-id before 'do'
18 | do
| ^~
Logarithmun.cpp:26:5: error: expected unqualified-id before 'while'
26 | while (Inkr>Limit);
| ^~~~~
Logarithmun.cpp:28:5: error: 'Result' does not name a type
28 | Result=std::round(Result*std::pow(10,prez))*std::pow(10,-prez);
| ^~~~~~
Logarithmun.cpp:29:10: error: 'cout' in namespace 'std' does not name a type
29 | std::cout<<std::setw(prez+3)<<std::setprecision(prez)<<std::fixed<<Result<<" \t"<<c<<'\n';
| ^~~~
C:/msys64/mingw64/include/c++/12.2.0/iostream:61:18: note: 'std::cout' declared here
61 | extern ostream cout; /// Linked to standard output
| ^~~~
Logarithmun.cpp:31:5: error: expected unqualified-id before 'return'
31 | return(0);
| ^~~~~~
Logarithmun.cpp:32:1: error: expected declaration before '}' token
32 | }
| ^
I did remove line 12, but the errors remain.
So I obviously changed inadvertently something fundamental but I cannot find the problem. I do not understand the error at all! I used similar code a lot already.

Related

How to handle errors when extracting data from untyped JSON in serde_json?

I have a serde_json::Value which I expect to contain an array of objects. From those objects I want to extract 2 values and return an error if anything fails. This is my code so far:
use std::collections::HashMap;
use anyhow::Result;
fn get_stock(response: serde_json::Value) -> Result<HashMap<String, u32>>{
response["products"]
.as_array()?.iter()
.map(|product| {
let product = product.as_object()?;
(
product["name"].as_str()?.to_owned(),
//as_u64 fails for some reason
product["stock"].as_str()?.parse::<u32>()?,
)
})
.collect()?
}
When I used .unwrap() this worked fine, but after changing the return type to Result and replacing unwraps with ? I'm getting the following compilation errors:
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
--> src/bin/products.rs:7:20
|
5 | / fn get_stock(response: serde_json::Value) -> Result<HashMap<String, u32>>{
6 | | response["products"]
7 | | .as_array()?.iter()
| | ^ use `.ok_or(...)?` to provide an error compatible with `Result<HashMap<std::string::String, u32>, anyhow::Error>`
8 | | .map(|product| {
... |
16 | | .collect()?
17 | | }
| |_- this function returns a `Result`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `Result<HashMap<std::string::String, u32>, anyhow::Error>`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:9:46
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
10 | | (
11 | | product["name"].as_str()?.to_owned(),
... |
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:11:41
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
... |
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:13:42
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
12 | | //as_u64 fails for some reason
13 | | product["stock"].as_str()?.parse::<u32>()?,
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:13:58
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
12 | | //as_u64 fails for some reason
13 | | product["stock"].as_str()?.parse::<u32>()?,
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
miav#battlestation catbot % cargo run --bin products
Compiling catbot v0.1.0 (/Users/miav/Documents/Personal/Projects/programming/catbot)
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
--> src/bin/products.rs:7:20
|
5 | / fn get_stock(response: serde_json::Value) -> Result<HashMap<String, u32>>{
6 | | response["products"]
7 | | .as_array()?.iter()
| | ^ use `.ok_or(...)?` to provide an error compatible with `Result<HashMap<std::string::String, u32>, anyhow::Error>`
8 | | .map(|product| {
... |
16 | | .collect()?
17 | | }
| |_- this function returns a `Result`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `Result<HashMap<std::string::String, u32>, anyhow::Error>`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:9:46
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
10 | | (
11 | | product["name"].as_str()?.to_owned(),
... |
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:11:41
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
... |
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:13:42
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
12 | | //as_u64 fails for some reason
13 | | product["stock"].as_str()?.parse::<u32>()?,
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Option<Infallible>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/products.rs:13:58
|
8 | .map(|product| {
| ______________-
9 | | let product = product.as_object()?;
10 | | (
11 | | product["name"].as_str()?.to_owned(),
12 | | //as_u64 fails for some reason
13 | | product["stock"].as_str()?.parse::<u32>()?,
| | ^ cannot use the `?` operator in a closure that returns `(std::string::String, u32)`
14 | | )
15 | | })
| |_________- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `FromResidual<Result<Infallible, ParseIntError>>` is not implemented for `(std::string::String, u32)`
= note: required by `from_residual`
error: aborting due to 5 previous errors
I don't know the exact structure of the JSON in advance, so I cannot parse it into a struct. All I know is that it is most likely an array of objects which have a name string field and a stock integer field, which I want to extract into a map. If that doesn't happen to be the case, then I want to return an error. What is the simplest way to do this?
UPDATE:
After following Lagerbaer's suggestions and doing some digging I came up with the following solution.
use anyhow::{anyhow, Result};
use std::collections::HashMap;
fn get_stock(response: serde_json::Value) -> Result<HashMap<String, u32>> {
response
.get("products")
.ok_or(anyhow!("'products' not found"))?
.as_array()
.ok_or(anyhow!("'products' is not an array"))?
.iter()
.map(|product| -> Result<(String, u32)> {
let product = product.as_object().unwrap();
Ok((
product
.get("name")
.ok_or(anyhow!("'name' not found"))?
.as_str()
.ok_or(anyhow!("'name' is not a string"))?
.trim()
.to_owned(),
//as_u64 fails for some reason
product
.get("stock")
.ok_or(anyhow!("'stock' not found"))?
.as_str()
.ok_or(anyhow!("'stock' is not a string"))?
.parse::<u32>()?,
))
})
.collect()
}
Used ok_or() to map Option to Result, had to use the anyhow! macro to make it compatible with the anyhow result type.
It also turns out that collect() actually accepts an iterator of
Result<(String, u32)> to produce a Result<HashMap<String, u32>> with the exact behavior I wanted, that is, returning the first error or the complete hash map if there were no errors.
So there's a couple issues here and the compiler tries its best to tell you.
I'll get you started on the first, and then I encourage you to try going it alone for a bit.
So the very first error is that, apparently, as_array returns an Option and not Result and, hence, you can't use the ? operator there.
Luckily, the compiler tells you what to do: Option has a method ok_or that you should call. It will turn the Option into Result. If the Option is Some(value) you'll get a Ok(value), and if the Option is None, you'll get whatever error you specified in the ok_or argument.
Another easy to spot mistake is this: Your function returns a Result, so the return value should, obviously, be a Result. Hence the very final last ? should be removed, because that ? would take a Result and turn it into the "pure" value (if the result was Ok).
And then what's left is to figure out exactly what the closure should return. Maybe you can try that after fixing the other mistakes that I explained above.

Connect Ruby and MySQL

trying to connect ruby and mysql. When running a basic script to access the database getting the error:
Unable to load driver 'Mysql' (underlying error: uninitialized constant DBI::DBD::Mysql) (DBI::InterfaceError)
Googled it and found solution:
gem install mysql
gem install dbd-mysql
First one, gives error:
checking for mysql_ssl_set()... yes
checking for rb_str_set_len()... yes
checking for rb_thread_start_timer()... no
checking for mysql.h... yes
creating Makefile
current directory: /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1/ext/mysql_api
make "DESTDIR=" clean
current directory: /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1/ext/mysql_api
make "DESTDIR="
compiling mysql.c
mysql.c:79:2: error: unknown type name ‘my_bool’
79 | my_bool *is_null;
| ^~~~~~~
mysql.c: In function ‘options’:
mysql.c:361:5: error: unknown type name ‘my_bool’; did you mean ‘bool’?
361 | my_bool b;
| ^~~~~~~
| bool
mysql.c:391:10: error: ‘MYSQL_SET_CLIENT_IP’ undeclared (first use in this function); did you mean ‘MYSQL_SET_CHARSET_DIR’?
391 | case MYSQL_SET_CLIENT_IP:
| ^~~~~~~~~~~~~~~~~~~
| MYSQL_SET_CHARSET_DIR
mysql.c:391:10: note: each undeclared identifier is reported only once for each function it appears in
mysql.c:398:10: error: ‘MYSQL_SECURE_AUTH’ undeclared (first use in this function); did you mean ‘MYSQL_DEFAULT_AUTH’?
398 | case MYSQL_SECURE_AUTH:
| ^~~~~~~~~~~~~~~~~
| MYSQL_DEFAULT_AUTH
mysql.c: In function ‘stmt_init’:
mysql.c:878:5: error: ‘my_bool’ undeclared (first use in this function)
878 | my_bool true = 1;
| ^~~~~~~
mysql.c:878:12: error: expected ‘;’ before numeric constant
878 | my_bool true = 1;
| ^
| ;
mysql.c:883:61: error: lvalue required as unary ‘&’ operand
883 | if (mysql_stmt_attr_set(s, STMT_ATTR_UPDATE_MAX_LENGTH, &true))
| ^
mysql.c: In function ‘stmt_bind_result’:
mysql.c:1320:74: error: ‘rb_cFixnum’ undeclared (first use in this function)
1320 | else if (argv[i] == rb_cNumeric || argv[i] == rb_cInteger || argv[i] == rb_cFixnum)
| ^~~~~~~~~~
mysql.c: In function ‘stmt_prepare’:
mysql.c:1681:32: warning: assignment to ‘_Bool *’ from incompatible pointer type ‘int *’ [-Wincompatible-pointer-types]
1681 | s->result.bind[i].is_null = &(s->result.is_null[i]);
| ^
In file included from /home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby.h:33,
from mysql.c:5:
mysql.c: In function ‘Init_mysql_api’:
mysql.c:2049:52: error: ‘MYSQL_SECURE_AUTH’ undeclared (first use in this function); did you mean ‘MYSQL_DEFAULT_AUTH’?
2049 | rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
| ^~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2049:44: note: in expansion of macro ‘INT2NUM’
2049 | rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
| ^~~~~~~
mysql.c:2050:61: error: ‘MYSQL_OPT_GUESS_CONNECTION’ undeclared (first use in this function); did you mean ‘MYSQL_OPT_RECONNECT’?
2050 | rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2050:53: note: in expansion of macro ‘INT2NUM’
2050 | rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
| ^~~~~~~
mysql.c:2051:68: error: ‘MYSQL_OPT_USE_EMBEDDED_CONNECTION’ undeclared (first use in this function)
2051 | rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2051:60: note: in expansion of macro ‘INT2NUM’
2051 | rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
| ^~~~~~~
mysql.c:2052:66: error: ‘MYSQL_OPT_USE_REMOTE_CONNECTION’ undeclared (first use in this function)
2052 | rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2052:58: note: in expansion of macro ‘INT2NUM’
2052 | rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
| ^~~~~~~
mysql.c:2053:54: error: ‘MYSQL_SET_CLIENT_IP’ undeclared (first use in this function); did you mean ‘MYSQL_SET_CHARSET_DIR’?
2053 | rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
| ^~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2053:46: note: in expansion of macro ‘INT2NUM’
2053 | rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
| ^~~~~~~
error_const.h:2661:27: error: ‘ER_XPLUGIN_IP’ undeclared (first use in this function); did you mean ‘ER_PLUGIN_OOM’?
2661 | rb_define_mysql_const(ER_XPLUGIN_IP);
| ^~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2286:62: note: in expansion of macro ‘INT2NUM’
2286 | #define rb_define_mysql_const(s) rb_define_const(eMysql, #s, INT2NUM(s))
| ^~~~~~~
error_const.h:2661:5: note: in expansion of macro ‘rb_define_mysql_const’
2661 | rb_define_mysql_const(ER_XPLUGIN_IP);
| ^~~~~~~~~~~~~~~~~~~~~
mysql.c: At top level:
cc1: note: unrecognized command-line option ‘-Wno-self-assign’ may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option ‘-Wno-parentheses-equality’ may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option ‘-Wno-constant-logical-operand’ may have been intended to silence earlier diagnostics
make: *** [Makefile:245: mysql.o] Error 1
make failed, exit code 2
Gem files will remain installed in /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1 for inspection.
Results logged to /home/wheatman/.rvm/gems/ruby-2.7.2/extensions/x86_64-linux/2.7.0/mysql-2.9.1/gem_make.out
And the second one gives another error:
Building native extensions. This could take a while...
ERROR: Error installing dbd-mysql:
ERROR: Failed to build gem native extension.
current directory: /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1/ext/mysql_api
/home/wheatman/.rvm/rubies/ruby-2.7.2/bin/ruby -I /home/wheatman/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0 -r ./siteconf20201219-250830-klyeov.rb extconf.rb
checking for mysql_ssl_set()... yes
checking for rb_str_set_len()... yes
checking for rb_thread_start_timer()... no
checking for mysql.h... yes
creating Makefile
current directory: /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1/ext/mysql_api
make "DESTDIR=" clean
current directory: /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1/ext/mysql_api
make "DESTDIR="
compiling mysql.c
mysql.c:79:2: error: unknown type name ‘my_bool’
79 | my_bool *is_null;
| ^~~~~~~
mysql.c: In function ‘options’:
mysql.c:361:5: error: unknown type name ‘my_bool’; did you mean ‘bool’?
361 | my_bool b;
| ^~~~~~~
| bool
mysql.c:391:10: error: ‘MYSQL_SET_CLIENT_IP’ undeclared (first use in this function); did you mean ‘MYSQL_SET_CHARSET_DIR’?
391 | case MYSQL_SET_CLIENT_IP:
| ^~~~~~~~~~~~~~~~~~~
| MYSQL_SET_CHARSET_DIR
mysql.c:391:10: note: each undeclared identifier is reported only once for each function it appears in
mysql.c:398:10: error: ‘MYSQL_SECURE_AUTH’ undeclared (first use in this function); did you mean ‘MYSQL_DEFAULT_AUTH’?
398 | case MYSQL_SECURE_AUTH:
| ^~~~~~~~~~~~~~~~~
| MYSQL_DEFAULT_AUTH
mysql.c: In function ‘stmt_init’:
mysql.c:878:5: error: ‘my_bool’ undeclared (first use in this function)
878 | my_bool true = 1;
| ^~~~~~~
mysql.c:878:12: error: expected ‘;’ before numeric constant
878 | my_bool true = 1;
| ^
| ;
mysql.c:883:61: error: lvalue required as unary ‘&’ operand
883 | if (mysql_stmt_attr_set(s, STMT_ATTR_UPDATE_MAX_LENGTH, &true))
| ^
mysql.c: In function ‘stmt_bind_result’:
mysql.c:1320:74: error: ‘rb_cFixnum’ undeclared (first use in this function)
1320 | else if (argv[i] == rb_cNumeric || argv[i] == rb_cInteger || argv[i] == rb_cFixnum)
| ^~~~~~~~~~
mysql.c: In function ‘stmt_prepare’:
mysql.c:1681:32: warning: assignment to ‘_Bool *’ from incompatible pointer type ‘int *’ [-Wincompatible-pointer-types]
1681 | s->result.bind[i].is_null = &(s->result.is_null[i]);
| ^
In file included from /home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby.h:33,
from mysql.c:5:
mysql.c: In function ‘Init_mysql_api’:
mysql.c:2049:52: error: ‘MYSQL_SECURE_AUTH’ undeclared (first use in this function); did you mean ‘MYSQL_DEFAULT_AUTH’?
2049 | rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
| ^~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2049:44: note: in expansion of macro ‘INT2NUM’
2049 | rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
| ^~~~~~~
mysql.c:2050:61: error: ‘MYSQL_OPT_GUESS_CONNECTION’ undeclared (first use in this function); did you mean ‘MYSQL_OPT_RECONNECT’?
2050 | rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2050:53: note: in expansion of macro ‘INT2NUM’
2050 | rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
| ^~~~~~~
mysql.c:2051:68: error: ‘MYSQL_OPT_USE_EMBEDDED_CONNECTION’ undeclared (first use in this function)
2051 | rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2051:60: note: in expansion of macro ‘INT2NUM’
2051 | rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
| ^~~~~~~
mysql.c:2052:66: error: ‘MYSQL_OPT_USE_REMOTE_CONNECTION’ undeclared (first use in this function)
2052 | rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2052:58: note: in expansion of macro ‘INT2NUM’
2052 | rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
| ^~~~~~~
mysql.c:2053:54: error: ‘MYSQL_SET_CLIENT_IP’ undeclared (first use in this function); did you mean ‘MYSQL_SET_CHARSET_DIR’?
2053 | rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
| ^~~~~~~~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2053:46: note: in expansion of macro ‘INT2NUM’
2053 | rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
| ^~~~~~~
error_const.h:2661:27: error: ‘ER_XPLUGIN_IP’ undeclared (first use in this function); did you mean ‘ER_PLUGIN_OOM’?
2661 | rb_define_mysql_const(ER_XPLUGIN_IP);
| ^~~~~~~~~~~~~
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:262:33: note: in definition of macro ‘RB_INT2FIX’
262 | #define RB_INT2FIX(i) (((VALUE)(i))<<1 | RUBY_FIXNUM_FLAG)
| ^
/home/wheatman/.rvm/rubies/ruby-2.7.2/include/ruby-2.7.0/ruby/ruby.h:1609:20: note: in expansion of macro ‘RB_INT2NUM’
1609 | #define INT2NUM(x) RB_INT2NUM(x)
| ^~~~~~~~~~
mysql.c:2286:62: note: in expansion of macro ‘INT2NUM’
2286 | #define rb_define_mysql_const(s) rb_define_const(eMysql, #s, INT2NUM(s))
| ^~~~~~~
error_const.h:2661:5: note: in expansion of macro ‘rb_define_mysql_const’
2661 | rb_define_mysql_const(ER_XPLUGIN_IP);
| ^~~~~~~~~~~~~~~~~~~~~
mysql.c: At top level:
cc1: note: unrecognized command-line option ‘-Wno-self-assign’ may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option ‘-Wno-parentheses-equality’ may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option ‘-Wno-constant-logical-operand’ may have been intended to silence earlier diagnostics
make: *** [Makefile:245: mysql.o] Error 1
make failed, exit code 2
Gem files will remain installed in /home/wheatman/.rvm/gems/ruby-2.7.2/gems/mysql-2.9.1 for inspection.
Results logged to /home/wheatman/.rvm/gems/ruby-2.7.2/extensions/x86_64-linux/2.7.0/mysql-2.9.1/gem_make.out
Am using Ubuntu 20.10, ruby 2.7.2 and mysql 8.0.22 and as far as I understand the problem in versions. Have someone encountered such problem? Is it versions issue? Any chance to connect ruby with mysql with my versions or I need to go back to older ones?
You're using extremely outdated and abandoned tools. The mysql gem has not seen a new release since 2013 and dbd-mysql has not been updated since 2010. Its highly questionable if they will work with modern versions of Ruby and MySQL.
What you want is the the mysql2 gem which is actively maintained.
# https://bundler.io/guides/bundler_in_a_single_file_ruby_script.html
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'mysql2', '~> 0.5.2'
end
client = Mysql2::Client.new(host: "localhost", username: "root")
results = client.query("SELECT * FROM users")
results.each do |row|
# do something with row, it's ready to rock
end

the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)

I am doing my assignment that's include make connection with the database in Rust. I am using the latest version of mysql crate: mysql ="18.2.0".My Database connection is successful as I print the pool variable. I write my own code for table student but I get the error. Then i paste the code of documentation, I recieve the following error with'?' operator:
I am connecting the database in rust for the first time. Any help is appreciated.
warning: unused import: `std::io`
--> src/main.rs:2:5
|
2 | use std::io;
| ^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:17:12
|
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
... |
58 | |
59 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:19:16
|
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
18 | |
19 | | let mut conn = pool.get_conn()?;
| | ^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
... |
58 | |
59 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:22:1
|
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
... |
22 | /| conn.query_drop(
23 | || r"CREATE TEMPORARY TABLE payment (
24 | || customer_id int not null,
25 | || amount int not null,
26 | || account_name text
27 | || )")?;
| ||________^ cannot use the `?` operator in a function that returns `()`
... |
58 | |
59 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:38:1
|
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
... |
38 | /| conn.exec_batch(
39 | || r"INSERT INTO payment (customer_id, amount, account_name)
40 | || VALUES (:customer_id, :amount, :account_name)",
41 | || payments.iter().map(|p| params! {
... ||
45 | || })
46 | || )?;
| ||__^ cannot use the `?` operator in a function that returns `()`
... |
58 | |
59 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:49:25
|
14 | / fn insert(){
15 | |
16 | |
17 | | let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
... |
49 | | let selected_payments = conn
| |_________________________^
50 | || .query_map(
51 | || "SELECT customer_id, amount, account_name from payment",
52 | || |(customer_id, amount, account_name)| {
53 | || Payment { customer_id, amount, account_name }
54 | || },
55 | || )?;
| ||______^ cannot use the `?` operator in a function that returns `()`
... |
58 | |
59 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`
error: aborting due to 5 previous errors; 1 warning emitted
For more information about this error, try `rustc --explain E0277`.
error: could not compile `class-09`.
Here is the code, i copy from documentation to test:
use std::io;
use mysql::prelude::*;
use mysql::*;
#[derive(Debug, PartialEq, Eq)]
struct Payment {
customer_id: i32,
amount: i32,
account_name: Option<String>,
}
fn insert(){
let pool = Pool::new("mysql://root:root#localhost:3306/Rust_testing")?;
let mut conn = pool.get_conn()?;
// Let's create a table for payments.
conn.query_drop(
r"CREATE TEMPORARY TABLE payment (
customer_id int not null,
amount int not null,
account_name text
)")?;
let payments = vec![
Payment { customer_id: 1, amount: 2, account_name: None },
Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) },
Payment { customer_id: 5, amount: 6, account_name: None },
Payment { customer_id: 7, amount: 8, account_name: None },
Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) },
];
// Now let's insert payments to the database
conn.exec_batch(
r"INSERT INTO payment (customer_id, amount, account_name)
VALUES (:customer_id, :amount, :account_name)",
payments.iter().map(|p| params! {
"customer_id" => p.customer_id,
"amount" => p.amount,
"account_name" => &p.account_name,
})
)?;
// Let's select payments from database. Type inference should do the trick here.
let selected_payments = conn
.query_map(
"SELECT customer_id, amount, account_name from payment",
|(customer_id, amount, account_name)| {
Payment { customer_id, amount, account_name }
},
)?;
println!("Yay!");
}
fn main(){
insert();
}
and when i write my code without the ? operator, I got the following error:
warning: unused import: `std::io`
--> src/main.rs:2:5
|
2 | use std::io;
| ^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0599]: no method named `query_drop` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
--> src/main.rs:32:6
|
32 | conn.query_drop(
| ^^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`
error[E0599]: no method named `exec_batch` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
--> src/main.rs:48:6
|
48 | conn.exec_batch(
| ^^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`
error[E0599]: no method named `query_map` found for enum `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>` in the current scope
--> src/main.rs:60:6
|
60 | .query_map(
| ^^^^^^^^^ method not found in `std::result::Result<mysql::conn::pool::PooledConn, mysql::error::Error>`
warning: unused import: `mysql::prelude`
--> src/main.rs:4:5
|
4 | use mysql::prelude::*;
| ^^^^^^^^^^^^^^
error: aborting due to 3 previous errors; 2 warnings emitted
For more information about this error, try `rustc --explain E0599`.
error: could not compile `class-09`.
As the compiler is telling you: you are missing a return type in your function.
The ? operator will return (propagate) the error if any, but for that to work you need to have a return type that can be constructed with the error type.
For prototyping, you can just call unwrap. But this approach should be carefully considered when writing production code, as it will just crash the program when the function returns an error.
find more here

How to call a function from another file and fetch in web

I'm new to Rust and still I am learning things. There is a rust application with main.rs and routes.rs. main.rs file has server configuration and routes.rs has methods with paths.
main.rs
#[macro_use]
extern crate log;
use actix_web::{App, HttpServer};
use dotenv::dotenv;
use listenfd::ListenFd;
use std::env;
mod search;
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
env_logger::init();
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(||
App::new()
.configure(search::init_routes)
);
server = match listenfd.take_tcp_listener(0)? {
Some(listener) => server.listen(listener)?,
None => {
let host = env::var("HOST").expect("Host not set");
let port = env::var("PORT").expect("Port not set");
server.bind(format!("{}:{}", host, port))?
}
};
info!("Starting server");
server.run().await
}
routes.rs
use crate::search::User;
use actix_web::{get, post, put, delete, web, HttpResponse, Responder};
use serde_json::json;
extern crate reqwest;
extern crate serde;
use reqwest::Error;
use serde::{Deserialize};
use rocket_contrib::json::Json;
use serde_json::Value;
// mod bargainfindermax;
#[get("/users")]
async fn find_all() -> impl Responder {
HttpResponse::Ok().json(
vec![
User { id: 1, email: "tore#cloudmaker.dev".to_string() },
User { id: 2, email: "tore#cloudmaker.dev".to_string() },
]
)
}
pub fn init_routes(cfg: &mut web::ServiceConfig) {
cfg.service(find_all);
}
Now what I want is I want to fetch an API using a method in another separate rs file (fetch_test.rs) and route it in the routes.rs file. Then I want to get the response from a web browser by running that route path(link).
How can I do these things ?? I searched everywhere, but I found nothing helpful. And sometimes I didn't understand some documentations also.
**Update.
fetch_test.rs
extern crate reqwest;
use hyper::header::{Headers, Authorization, Basic, ContentType};
pub fn authenticate() -> String {
fn construct_headers() -> Headers {
let mut headers = Headers::new();
headers.set(
Authorization(
Basic {
username: "HI:ABGTYH".to_owned(),
password: Some("%8YHT".to_owned())
}
)
);
headers.set(ContentType::form_url_encoded());
headers
}
let client = reqwest::Client::new();
let resz = client.post("https://api.test.com/auth/token")
.headers(construct_headers())
.body("grant_type=client_credentials")
.json(&map)
.send()
.await?;
}
Errors.
Compiling sabre-actix-kist v0.1.0 (E:\wamp64\www\BukFlightsNewLevel\flights\APIs\sabre-actix-kist)
error[E0425]: cannot find value `map` in this scope
--> src\search\routes\common.rs:28:12
|
28 | .json(&map)
| ^^^ not found in this scope
error[E0728]: `await` is only allowed inside `async` functions and blocks
--> src\search\routes\common.rs:25:12
|
4 | pub fn authenticate() -> String {
| ------------ this is not `async`
...
25 | let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
| ____________^
26 | | .headers(construct_headers())
27 | | .body("grant_type=client_credentials")
28 | | .json(&map)
29 | | .send()
30 | | .await?;
| |__________^ only allowed inside `async` functions and blocks
error[E0277]: the trait bound `std::result::Result<search::routes::reqwest::Response, search::routes::reqwest::Error>: std::future::Future` is not satisfied
--> src\search\routes\common.rs:25:12
|
25 | let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
| ____________^
26 | | .headers(construct_headers())
27 | | .body("grant_type=client_credentials")
28 | | .json(&map)
29 | | .send()
30 | | .await?;
| |__________^ the trait `std::future::Future` is not implemented for `std::result::Result<search::routes::reqwest::Response, search::routes::reqwest::Error>`
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src\search\routes\common.rs:25:12
|
4 | / pub fn authenticate() -> String {
5 | |
6 | | let res = reqwest::get("http://api.github.com/users")
7 | | .expect("Couldnt")
... |
25 | | let resz = client.post("https://api-crt.cert.havail.sabre.com/v2/auth/token")
| |____________^
26 | || .headers(construct_headers())
27 | || .body("grant_type=client_credentials")
28 | || .json(&map)
29 | || .send()
30 | || .await?;
| ||___________^ cannot use the `?` operator in a function that returns `std::string::String`
31 | |
32 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `std::ops::Try` is not implemented for `std::string::String`
= note: required by `std::ops::Try::from_error`
error[E0308]: mismatched types
--> src\search\routes\common.rs:4:26
|
4 | pub fn authenticate() -> String {
| ------------ ^^^^^^ expected struct `std::string::String`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
**Update Again.
extern crate reqwest;
use hyper::header::{Headers, Authorization, Basic, ContentType};
fn construct_headers() -> Headers {
let mut headers = Headers::new();
headers.set(
Authorization(
Basic {
username: "HI:ABGTYH".to_owned(),
password: Some("%8YHT".to_owned())
}
)
);
headers.set(ContentType::form_url_encoded());
headers
}
pub async fn authenticate() -> Result<String, reqwest::Error> {
let client = reqwest::Client::new();
let resz = client.post("https://api.test.com/auth/token")
.headers(construct_headers())
.body("grant_type=client_credentials")
.json(&map)
.send()
.await?;
}
**New Error.
error[E0425]: cannot find value `map` in this scope
--> src\search\routes\common.rs:24:12
|
24 | .json(&map)
| ^^^ not found in this scope
error[E0277]: the trait bound `impl std::future::Future: search::routes::serde::Serialize` is not satisfied
--> src\search\routes.rs:24:29
|
24 | HttpResponse::Ok().json(set_token)
| ^^^^^^^^^ the trait `search::routes::serde::Serialize` is not implemented for `impl std::future::Future`
error[E0308]: mismatched types
--> src\search\routes\common.rs:22:14
|
22 | .headers(construct_headers())
| ^^^^^^^^^^^^^^^^^^^ expected struct `search::routes::reqwest::header::HeaderMap`, found struct `hyper::header::Headers`
|
= note: expected struct `search::routes::reqwest::header::HeaderMap`
found struct `hyper::header::Headers`
error[E0599]: no method named `json` found for struct `search::routes::reqwest::RequestBuilder` in the current scope
--> src\search\routes\common.rs:24:6
|
24 | .json(&map)
| ^^^^ method not found in `search::routes::reqwest::RequestBuilder`
error[E0308]: mismatched types
--> src\search\routes\common.rs:18:63
|
18 | pub async fn authenticate() -> Result<String, reqwest::Error> {
| _______________________________________________________________^
19 | |
20 | | let client = reqwest::Client::new();
21 | | let resz = client.post("https://api.test.com/auth/token")
... |
27 | |
28 | | }
| |_^ expected enum `std::result::Result`, found `()`
|
= note: expected enum `std::result::Result<std::string::String, search::routes::reqwest::Error>`
found unit type `()`
Can I clarify your question? As I understand you already know how to use functions from another file. Do you need to know how to make API requests and pass a result form a request as Response?
Firstly, you need to create fetch_test.rs with using for example reqwest lib:
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.json(&map)
.send()
.await?;
Map result or pass it as it is.
Return result in routes.rs: HttpResponse::Ok().json(res)
I hope it will help you.

I am trying add a background image in css, but I'm getting the following error

Failed to compile.
ERROR :
./src/app/shopping-list/shopping-edit/shopping-edit.component.css
Module Error (from ./node_modules/postcss-loader/src/index.js):
(Emitted value instead of an instance of Error) CssSyntaxError:
D:\demoApp\src\app\shopping-list\shopping-edit\shopping-edit.component.css:98:26:
Can't resolve 'assets/header.png' in
'D:\demoApp\src\app\shopping-list\shopping-edit'
CODE :
96 | }
97 | .section-testimonials{
> 98 | background-image:url(assets/header.png); ;
| ^
99 | }
100 |
Use quotes and a forward slash in the location:
96 | }
97 | .section-testimonials{
> 98 | background-image:url("./assets/header.png"); ;
|
99 | }
100 |