我正在尝试创建仅FnOnce
的函数。
以下代码段不起作用:
// Attempt 1
// Error doesn't have a size known at compile-time
let f: FnOnce() -> () = || println!("Hello");
// Attempt 2
fn g<T: FnOnce() -> ()>(c: T) -> (FnOnce() -> ()) {
c
}
// Error: doesn't have a size known at compile-time
let f = g(|| println!("Hello"));
// Attempt 3
// Error: cast to unsized type
let f = (|| println!("Hello")) as (FnOnce() -> ());
答案 0 :(得分:1)
'VBA Open excel to copy TC to master list Dir
Sub Copy_Paste__To_New_Sheet()
'Variable Declaration
Dim sFilePath As String
Dim sFileName As String
Dim wb As Excel.Workbook
Dim rngCopy As Range, acell As Range, bcell As Range
Dim strSearch As String
Dim strFile As Variant
Dim wb2 As Excel.Workbook
'Specify File Path
sFilePath = "C:\temp\new"
'Check for back slash
If Right(sFilePath, 1) <> "\" Then
sFilePath = sFilePath & "\"
End If
sFileName = Dir(sFilePath)
Do While Len(sFileName) > 0
Set rngCopy = Nothing
Application.DisplayAlerts = False
Set wb = Workbooks.Open(Filename:=sFilePath & sFileName)
Sheets("TestCases").Activate
' Range("E:E").Insert
'Display file name in immediate window
' Debug.Print sFileName
strSearch = "TC1"
Set WS = Worksheets("TestCases")
With WS
Set acell = .Columns(1).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not acell Is Nothing Then
Set bcell = acell
If rngCopy Is Nothing Then
Set rngCopy = WS.Range(WS.Cells(acell.Row + 1, 1), WS.Cells(acell.Row + 2, 4))
Else
Set rngCopy = Application.Union(rngCopy, .Rows((acell.Row + 1) & ":" & (acell.Row + 2)))
End If
Do
Set acell = .Columns(1).FindNext(After:=acell)
If Not acell Is Nothing Then
If acell.Address = bcell.Address Then Exit Do
If rngCopy Is Nothing Then
Set rngCopy = WS.Range(WS.Cells(acell.Row + 1, 1), WS.Cells(acell.Row + 2, 4))
Else
Set rngCopy = Application.Union(rngCopy, .Rows((acell.Row + 1) & ":" & (acell.Row + 2)))
End If
Else
Exit Do
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
'~~> I am pasting to Output sheet. Change as applicable
Set wb2 = Workbooks.Open("C:\temp\output\outputtest.xlsx")
If Not rngCopy Is Nothing Then Sheets("Output").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(rngCopy.Rows.Count, 4).Value = rngCopy.Value
' If Not rngCopy Is Nothing Then Sheets("Output").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(1, 4).Value = rngCopy.Value
' If Not rngCopy Is Nothing Then rngCopy.Copy Sheets("Output").Cells(1, 1).Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
' .End (xlDown) + 1
' Sheets("Output").Rows(1)
Application.DisplayAlerts = False
wb2.Close savechanges = False
End With
是闭包的特征,闭包只能被调用一次,通常是因为捕获的值被移入闭包,并且在调用期间被消耗。例如,我们可以捕获一个值并将其作为返回值移出:
FnOnce
请注意,fn delay<A: 'static>(a: A) -> Box<dyn FnOnce() -> A> {
Box::new(move || a)
}
fn main() {
let a = "hello".to_string();
let f = delay(a);
println!("{}", f());
}
关键字不是严格必需的。编译器发现move
需要移到闭包中才能作为值返回并移出。