我想写这样的代码:
def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> &("--------FormDataBoundary" <> &1)
end
但它没有用。
答案 0 :(得分:63)
看起来有点奇怪但必须工作:
def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> (&("--------FormDataBoundary" <> &1)).()
end
答案 1 :(得分:10)
相关:如果&#34;匿名&#34;函数已分配给变量,您可以像这样管道:
def boundary do
add_marker = fn (s) ->
"--------FormDataBoundary" <> s
end
:crypto.rand_bytes(8)
|> Base.encode16
|> add_marker.()
end
答案 2 :(得分:1)
可接受的答案有效,但是您可以使用
(&"--------FormDataBoundary#{&1}").()
代替
(&("--------FormDataBoundary" <> &1)).()
以下是全部功能:
def boundary do
:crypto.strong_rand_bytes(8)
|> Base.encode16()
|> (&"--------FormDataBoundary#{&1}").()
end
奖金:我还用:crypto.rand_bytes/1
替换了:crypto.strong_rand_bytes/1
(在elixir 1.6+中不存在)。
答案 3 :(得分:0)
你真的不能走吗?
thing
|> func_one()
|> fn input -> do_stuff_here() end)
您可以做一些事情,例如将事情直接输送到类似情况的情况下
thing
|> func_one()
|> case do
所以,我认为您可以将其传递给匿名函数。
答案 4 :(得分:0)
您还可以使用类似这样的内容:
C:\Users\X\Desktop>python so59568543.py
usage: so59568543.py [-h] file1 file2
so59568543.py: error: the following arguments are required: file1, file2
C:\Users\X\Desktop>python so59568543.py -h
usage: so59568543.py [-h] file1 file2
... blah blah ...
positional arguments:
file1 ... blah blah ...
file2 ... blah blah ...
optional arguments:
-h, --help show this help message and exit
C:\Users\X\Desktop>python so59568543.py aaa bbb
Namespace(file1='aaa', file2='bbb')
C:\Users\X\Desktop>
这种形式相对于其他形式的一个优点是,您可以轻松编写简单的“ case”语句:
def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> (fn chars -> "--------FormDataBoundary" <> chars end).()
end
发件人:
与上述couchemar's answer相比,使用def do_some_stuff do
something
|> a_named_function()
|> (
fn
{:ok, something} -> something
{:error, something_else} ->
Logger.error "Error"
# ...
end
).()
end
的位置小:
fn
...但是,对于您的特定示例,使用def boundary do
:crypto.rand_bytes(8)
|> Base.encode16
|> (&("--------FormDataBoundary" <> &1)).()
end
的上述形式可能是最好的。如果管道表达式更复杂,则命名匿名函数参数可能会更有用。
我的回答也比Nathan Long's answer更简洁:
&
...如果由于某种原因您需要在管道中多次调用该函数,他的答案会更好。